diff --git a/app/modules/api/Controllers/Account/AccountBase.php b/app/modules/api/Controllers/Account/AccountBase.php index 59f00496..94052a46 100644 --- a/app/modules/api/Controllers/Account/AccountBase.php +++ b/app/modules/api/Controllers/Account/AccountBase.php @@ -32,6 +32,7 @@ use SP\Domain\Account\Adapters\AccountAdapterInterface; use SP\Domain\Account\Ports\AccountPresetServiceInterface; use SP\Domain\Account\Ports\AccountServiceInterface; use SP\Domain\Api\Ports\ApiServiceInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Exceptions\InvalidClassException; use SP\Domain\CustomField\Ports\CustomFieldServiceInterface; use SP\Modules\Api\Controllers\ControllerBase; @@ -51,14 +52,14 @@ abstract class AccountBase extends ControllerBase * @throws InvalidClassException */ public function __construct( - Application $application, - Klein $router, - ApiServiceInterface $apiService, - Acl $acl, + Application $application, + Klein $router, + ApiServiceInterface $apiService, + AclInterface $acl, AccountPresetServiceInterface $accountPresetService, - AccountServiceInterface $accountService, + AccountServiceInterface $accountService, CustomFieldServiceInterface $customFieldService, - AccountAdapterInterface $accountAdapter + AccountAdapterInterface $accountAdapter ) { parent::__construct($application, $router, $apiService, $acl); diff --git a/app/modules/api/Controllers/Account/SearchController.php b/app/modules/api/Controllers/Account/SearchController.php index 9a467877..d3d168e2 100644 --- a/app/modules/api/Controllers/Account/SearchController.php +++ b/app/modules/api/Controllers/Account/SearchController.php @@ -35,6 +35,7 @@ use SP\Domain\Api\Ports\ApiServiceInterface; use SP\Domain\Api\Services\ApiResponse; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Core\Acl\AclActionsInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Modules\Api\Controllers\ControllerBase; /** @@ -45,10 +46,10 @@ final class SearchController extends ControllerBase private AccountSearchServiceInterface $accountSearchService; public function __construct( - Application $application, - Klein $router, + Application $application, + Klein $router, ApiServiceInterface $apiService, - Acl $acl, + AclInterface $acl, AccountSearchServiceInterface $accountSearchService ) { parent::__construct($application, $router, $apiService, $acl); diff --git a/app/modules/api/Controllers/Category/CategoryBase.php b/app/modules/api/Controllers/Category/CategoryBase.php index 24d9b94e..723b7f9c 100644 --- a/app/modules/api/Controllers/Category/CategoryBase.php +++ b/app/modules/api/Controllers/Category/CategoryBase.php @@ -31,6 +31,7 @@ use SP\Core\Application; use SP\Domain\Api\Ports\ApiServiceInterface; use SP\Domain\Category\Ports\CategoryAdapterInterface; use SP\Domain\Category\Ports\CategoryServiceInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Exceptions\InvalidClassException; use SP\Modules\Api\Controllers\ControllerBase; use SP\Modules\Api\Controllers\Help\CategoryHelp; @@ -47,10 +48,10 @@ abstract class CategoryBase extends ControllerBase * @throws InvalidClassException */ public function __construct( - Application $application, - Klein $router, + Application $application, + Klein $router, ApiServiceInterface $apiService, - Acl $acl, + AclInterface $acl, CategoryServiceInterface $categoryService, CategoryAdapterInterface $categoryAdapter ) { diff --git a/app/modules/api/Controllers/Client/ClientBase.php b/app/modules/api/Controllers/Client/ClientBase.php index 437d0ee7..2fefe616 100644 --- a/app/modules/api/Controllers/Client/ClientBase.php +++ b/app/modules/api/Controllers/Client/ClientBase.php @@ -31,6 +31,7 @@ use SP\Core\Application; use SP\Domain\Api\Ports\ApiServiceInterface; use SP\Domain\Client\Ports\ClientAdapterInterface; use SP\Domain\Client\Ports\ClientServiceInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Exceptions\InvalidClassException; use SP\Modules\Api\Controllers\ControllerBase; use SP\Modules\Api\Controllers\Help\ClientHelp; @@ -50,7 +51,7 @@ abstract class ClientBase extends ControllerBase Application $application, Klein $router, ApiServiceInterface $apiService, - Acl $acl, + AclInterface $acl, ClientServiceInterface $clientService, ClientAdapterInterface $clientAdapter ) { diff --git a/app/modules/api/Controllers/Config/BackupController.php b/app/modules/api/Controllers/Config/BackupController.php index 01476bf4..fc9450ea 100644 --- a/app/modules/api/Controllers/Config/BackupController.php +++ b/app/modules/api/Controllers/Config/BackupController.php @@ -33,6 +33,7 @@ use SP\Core\Events\EventMessage; use SP\Domain\Api\Ports\ApiServiceInterface; use SP\Domain\Api\Services\ApiResponse; use SP\Domain\Core\Acl\AclActionsInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Exceptions\InvalidClassException; use SP\Domain\Export\Ports\FileBackupServiceInterface; use SP\Domain\Export\Services\BackupFiles; @@ -52,10 +53,10 @@ final class BackupController extends ControllerBase * @throws InvalidClassException */ public function __construct( - Application $application, - Klein $router, + Application $application, + Klein $router, ApiServiceInterface $apiService, - Acl $acl, + AclInterface $acl, FileBackupServiceInterface $fileBackupService ) { parent::__construct($application, $router, $apiService, $acl); diff --git a/app/modules/api/Controllers/Config/ExportController.php b/app/modules/api/Controllers/Config/ExportController.php index dffa195e..55e55d1f 100644 --- a/app/modules/api/Controllers/Config/ExportController.php +++ b/app/modules/api/Controllers/Config/ExportController.php @@ -34,6 +34,7 @@ use SP\Core\Events\EventMessage; use SP\Domain\Api\Ports\ApiServiceInterface; use SP\Domain\Api\Services\ApiResponse; use SP\Domain\Core\Acl\AclActionsInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Exceptions\InvalidClassException; use SP\Domain\Export\Ports\XmlExportServiceInterface; use SP\Modules\Api\Controllers\ControllerBase; @@ -50,10 +51,10 @@ final class ExportController extends ControllerBase * @throws InvalidClassException */ public function __construct( - Application $application, - Klein $router, + Application $application, + Klein $router, ApiServiceInterface $apiService, - Acl $acl, + AclInterface $acl, XmlExportServiceInterface $xmlExportService ) { parent::__construct($application, $router, $apiService, $acl); diff --git a/app/modules/api/Controllers/ControllerBase.php b/app/modules/api/Controllers/ControllerBase.php index f2eba51e..76352efc 100644 --- a/app/modules/api/Controllers/ControllerBase.php +++ b/app/modules/api/Controllers/ControllerBase.php @@ -36,6 +36,7 @@ use SP\Domain\Api\Services\ApiResponse; use SP\Domain\Api\Services\JsonRpcResponse; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Config\Ports\ConfigDataInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Context\ContextInterface; use SP\Domain\Core\Exceptions\SPException; use SP\Http\JsonResponse; @@ -64,7 +65,7 @@ abstract class ControllerBase Application $application, Klein $router, ApiServiceInterface $apiService, - Acl $acl + AclInterface $acl ) { $this->context = $application->getContext(); $this->configData = $application->getConfig()->getConfigData(); diff --git a/app/modules/api/Controllers/Tag/TagBase.php b/app/modules/api/Controllers/Tag/TagBase.php index 0c51fb85..6172d2a0 100644 --- a/app/modules/api/Controllers/Tag/TagBase.php +++ b/app/modules/api/Controllers/Tag/TagBase.php @@ -29,6 +29,7 @@ use Klein\Klein; use SP\Core\Acl\Acl; use SP\Core\Application; use SP\Domain\Api\Ports\ApiServiceInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Exceptions\InvalidClassException; use SP\Domain\Tag\Ports\TagServiceInterface; use SP\Modules\Api\Controllers\ControllerBase; @@ -45,10 +46,10 @@ abstract class TagBase extends ControllerBase * @throws InvalidClassException */ public function __construct( - Application $application, - Klein $router, + Application $application, + Klein $router, ApiServiceInterface $apiService, - Acl $acl, + AclInterface $acl, TagServiceInterface $tagService ) { parent::__construct($application, $router, $apiService, $acl); diff --git a/app/modules/api/Controllers/UserGroup/UserGroupBase.php b/app/modules/api/Controllers/UserGroup/UserGroupBase.php index 07b778a9..fa611234 100644 --- a/app/modules/api/Controllers/UserGroup/UserGroupBase.php +++ b/app/modules/api/Controllers/UserGroup/UserGroupBase.php @@ -28,6 +28,7 @@ use Klein\Klein; use SP\Core\Acl\Acl; use SP\Core\Application; use SP\Domain\Api\Ports\ApiServiceInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Exceptions\InvalidClassException; use SP\Domain\User\Ports\UserGroupServiceInterface; use SP\Modules\Api\Controllers\ControllerBase; @@ -44,10 +45,10 @@ abstract class UserGroupBase extends ControllerBase * @throws InvalidClassException */ public function __construct( - Application $application, - Klein $router, + Application $application, + Klein $router, ApiServiceInterface $apiService, - Acl $acl, + AclInterface $acl, UserGroupServiceInterface $groupService ) { parent::__construct($application, $router, $apiService, $acl); diff --git a/app/modules/web/Controllers/AccountManager/BulkEditController.php b/app/modules/web/Controllers/AccountManager/BulkEditController.php index cbe282b4..a228392a 100644 --- a/app/modules/web/Controllers/AccountManager/BulkEditController.php +++ b/app/modules/web/Controllers/AccountManager/BulkEditController.php @@ -133,11 +133,11 @@ final class BulkEditController extends ControllerBase $this->view->assign('nextAction', Acl::getActionRoute(AclActionsInterface::ITEMS_MANAGE)); - $clients = SelectItemAdapter::factory($this->clientService->getAllBasic())->getItemsFromModel(); - $categories = SelectItemAdapter::factory($this->categoryService->getAllBasic())->getItemsFromModel(); - $tags = SelectItemAdapter::factory($this->tagService->getAllBasic())->getItemsFromModel(); - $users = SelectItemAdapter::factory($this->userService->getAllBasic())->getItemsFromModel(); - $userGroups = SelectItemAdapter::factory($this->userGroupService->getAllBasic())->getItemsFromModel(); + $clients = SelectItemAdapter::factory($this->clientService->getAll())->getItemsFromModel(); + $categories = SelectItemAdapter::factory($this->categoryService->getAll())->getItemsFromModel(); + $tags = SelectItemAdapter::factory($this->tagService->getAll())->getItemsFromModel(); + $users = SelectItemAdapter::factory($this->userService->getAll())->getItemsFromModel(); + $userGroups = SelectItemAdapter::factory($this->userGroupService->getAll())->getItemsFromModel(); $this->view->assign('users', $users); $this->view->assign('userGroups', $userGroups); diff --git a/app/modules/web/Controllers/AuthToken/AuthTokenViewBase.php b/app/modules/web/Controllers/AuthToken/AuthTokenViewBase.php index 24fd93de..23ef5116 100644 --- a/app/modules/web/Controllers/AuthToken/AuthTokenViewBase.php +++ b/app/modules/web/Controllers/AuthToken/AuthTokenViewBase.php @@ -25,15 +25,16 @@ namespace SP\Modules\Web\Controllers\AuthToken; -use SP\Core\Acl\Acl; use SP\Core\Application; -use SP\DataModel\AuthToken; +use SP\Domain\Auth\Models\AuthToken; +use SP\Domain\Auth\Ports\AuthTokenActionInterface; use SP\Domain\Auth\Ports\AuthTokenServiceInterface; -use SP\Domain\Auth\Services\AuthTokenService; +use SP\Domain\Auth\Services\AuthException; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Core\Acl\AclActionsInterface; use SP\Domain\Core\Exceptions\ConstraintException; use SP\Domain\Core\Exceptions\QueryException; +use SP\Domain\Core\Exceptions\SessionTimeout; use SP\Domain\Core\Exceptions\SPException; use SP\Domain\CustomField\Ports\CustomFieldServiceInterface; use SP\Domain\User\Ports\UserServiceInterface; @@ -51,28 +52,27 @@ abstract class AuthTokenViewBase extends ControllerBase use ItemTrait; use JsonTrait; - private AuthTokenServiceInterface $authTokenService; - private CustomFieldServiceInterface $customFieldService; - private UserServiceInterface $userService; - + /** + * @throws AuthException + * @throws SessionTimeout + */ public function __construct( - Application $application, - WebControllerHelper $webControllerHelper, - CustomFieldServiceInterface $customFieldService, - UserServiceInterface $userService + Application $application, + WebControllerHelper $webControllerHelper, + private readonly CustomFieldServiceInterface $customFieldService, + private readonly UserServiceInterface $userService, + private readonly AuthTokenServiceInterface $authTokenService, + private readonly AuthTokenActionInterface $authTokenAction, ) { parent::__construct($application, $webControllerHelper); $this->checkLoggedIn(); - - $this->customFieldService = $customFieldService; - $this->userService = $userService; } /** * Sets view data for displaying auth token's data * - * @param int|null $authTokenId + * @param int|null $authTokenId * * @throws ConstraintException * @throws QueryException @@ -91,18 +91,18 @@ abstract class AuthTokenViewBase extends ControllerBase $this->view->assign( 'users', - SelectItemAdapter::factory($this->userService->getAllBasic()) - ->getItemsFromModelSelected([$authToken->getUserId()]) + SelectItemAdapter::factory($this->userService->getAll()) + ->getItemsFromModelSelected([$authToken->getUserId()]) ); $this->view->assign( 'actions', - SelectItemAdapter::factory(AuthTokenService::getTokenActions()) - ->getItemsFromArraySelected([$authToken->getActionId()]) + SelectItemAdapter::factory($this->authTokenAction->getTokenActions()) + ->getItemsFromArraySelected([$authToken->getActionId()]) ); $this->view->assign( 'nextAction', - Acl::getActionRoute(AclActionsInterface::ACCESS_MANAGE) + $this->acl->getRouteFor(AclActionsInterface::ACCESS_MANAGE) ); if ($this->view->isView === true) { diff --git a/app/modules/web/Controllers/ConfigLdap/ImportController.php b/app/modules/web/Controllers/ConfigLdap/ImportController.php index 7e6a4bec..e251cabb 100644 --- a/app/modules/web/Controllers/ConfigLdap/ImportController.php +++ b/app/modules/web/Controllers/ConfigLdap/ImportController.php @@ -34,6 +34,7 @@ use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\PhpExtensionChecker; use SP\Domain\Core\Acl\AclActionsInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Acl\UnauthorizedPageException; use SP\Domain\Core\Exceptions\CheckException; use SP\Domain\Core\Exceptions\SessionTimeout; @@ -58,11 +59,11 @@ final class ImportController extends SimpleControllerBase private LdapImportServiceInterface $ldapImportService; public function __construct( - Application $application, - ThemeInterface $theme, - Klein $router, - Acl $acl, - RequestInterface $request, + Application $application, + ThemeInterface $theme, + Klein $router, + AclInterface $acl, + RequestInterface $request, PhpExtensionChecker $extensionChecker, LdapImportServiceInterface $ldapImportService ) { diff --git a/app/modules/web/Controllers/ConfigManager/IndexController.php b/app/modules/web/Controllers/ConfigManager/IndexController.php index 1a24e95e..cafee440 100644 --- a/app/modules/web/Controllers/ConfigManager/IndexController.php +++ b/app/modules/web/Controllers/ConfigManager/IndexController.php @@ -217,15 +217,15 @@ final class IndexController extends ControllerBase ); $template->assign( 'users', - SelectItemAdapter::factory($this->userService->getAllBasic())->getItemsFromModel() + SelectItemAdapter::factory($this->userService->getAll())->getItemsFromModel() ); $template->assign( 'userGroups', - SelectItemAdapter::factory($this->userGroupService->getAllBasic())->getItemsFromModel() + SelectItemAdapter::factory($this->userGroupService->getAll())->getItemsFromModel() ); $template->assign( 'userProfiles', - SelectItemAdapter::factory($this->userProfileService->getAllBasic())->getItemsFromModel() + SelectItemAdapter::factory($this->userProfileService->getAll())->getItemsFromModel() ); $template->assign('curlIsAvailable', $this->extensionChecker->checkCurl()); @@ -313,11 +313,11 @@ final class IndexController extends ControllerBase ); $template->assign( 'userGroups', - SelectItemAdapter::factory($this->userGroupService->getAllBasic())->getItemsFromModel() + SelectItemAdapter::factory($this->userGroupService->getAll())->getItemsFromModel() ); $template->assign( 'userProfiles', - SelectItemAdapter::factory($this->userProfileService->getAllBasic())->getItemsFromModel() + SelectItemAdapter::factory($this->userProfileService->getAll())->getItemsFromModel() ); $serverTypes = [ @@ -372,11 +372,11 @@ final class IndexController extends ControllerBase $template->assign('mailSecurity', ['SSL', 'TLS']); $template->assign( 'userGroups', - SelectItemAdapter::factory($this->userGroupService->getAllBasic())->getItemsFromModel() + SelectItemAdapter::factory($this->userGroupService->getAll())->getItemsFromModel() ); $template->assign( 'userProfiles', - SelectItemAdapter::factory($this->userProfileService->getAllBasic())->getItemsFromModel() + SelectItemAdapter::factory($this->userProfileService->getAll())->getItemsFromModel() ); $mailEvents = $this->configData->getMailEvents(); @@ -443,7 +443,7 @@ final class IndexController extends ControllerBase $template->assign( 'userGroups', - SelectItemAdapter::factory($this->userGroupService->getAllBasic())->getItemsFromModel() + SelectItemAdapter::factory($this->userGroupService->getAll())->getItemsFromModel() ); return new DataTab(__('Encryption'), $template); @@ -535,12 +535,12 @@ final class IndexController extends ControllerBase $template->assign( 'userGroups', - SelectItemAdapter::factory($this->userGroupService->getAllBasic()) + SelectItemAdapter::factory($this->userGroupService->getAll()) ->getItemsFromModelSelected([$this->userData->getUserGroupId()]) ); $template->assign( 'users', - SelectItemAdapter::factory($this->userService->getAllBasic()) + SelectItemAdapter::factory($this->userService->getAll()) ->getItemsFromModelSelected([$this->userData->getId()]) ); diff --git a/app/modules/web/Controllers/ControllerBase.php b/app/modules/web/Controllers/ControllerBase.php index 814e1748..0c0917b4 100644 --- a/app/modules/web/Controllers/ControllerBase.php +++ b/app/modules/web/Controllers/ControllerBase.php @@ -27,20 +27,20 @@ namespace SP\Modules\Web\Controllers; defined('APP_ROOT') || die(); use Exception; -use SP\Core\Acl\Acl; use SP\Core\Application; use SP\Core\Bootstrap\BootstrapBase; use SP\Core\Crypt\Hash; use SP\Core\Events\EventDispatcher; -use SP\Core\PhpExtensionChecker; use SP\DataModel\ProfileData; use SP\Domain\Auth\Services\AuthException; use SP\Domain\Config\Ports\ConfigDataInterface; -use SP\Domain\Config\Services\ConfigFileService; +use SP\Domain\Config\Ports\ConfigInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Context\SessionContextInterface; use SP\Domain\Core\Exceptions\FileNotFoundException; use SP\Domain\Core\Exceptions\SessionTimeout; use SP\Domain\Core\Exceptions\SPException; +use SP\Domain\Core\PhpExtensionCheckerInterface; use SP\Domain\Core\UI\ThemeInterface; use SP\Domain\Http\RequestInterface; use SP\Domain\User\Services\UserLoginResponse; @@ -63,21 +63,21 @@ abstract class ControllerBase protected const ERR_UNAVAILABLE = 0; - protected EventDispatcher $eventDispatcher; - protected ConfigFileService $config; - protected SessionContextInterface $session; - protected ThemeInterface $theme; - protected Acl $acl; - protected ConfigDataInterface $configData; - protected RequestInterface $request; - protected PhpExtensionChecker $extensionChecker; - protected TemplateInterface $view; - protected ?UserLoginResponse $userData = null; - protected ?ProfileData $userProfileData = null; - protected bool $isAjax; - protected LayoutHelper $layoutHelper; - protected string $actionName; - private BrowserAuthInterface $browser; + protected EventDispatcher $eventDispatcher; + protected ConfigInterface $config; + protected SessionContextInterface $session; + protected ThemeInterface $theme; + protected AclInterface $acl; + protected ConfigDataInterface $configData; + protected RequestInterface $request; + protected PhpExtensionCheckerInterface $extensionChecker; + protected TemplateInterface $view; + protected ?UserLoginResponse $userData = null; + protected ?ProfileData $userProfileData = null; + protected bool $isAjax; + protected LayoutHelper $layoutHelper; + protected string $actionName; + private BrowserAuthInterface $browser; public function __construct( Application $application, diff --git a/app/modules/web/Controllers/CustomField/CustomFieldViewBase.php b/app/modules/web/Controllers/CustomField/CustomFieldViewBase.php index c124de03..dac163eb 100644 --- a/app/modules/web/Controllers/CustomField/CustomFieldViewBase.php +++ b/app/modules/web/Controllers/CustomField/CustomFieldViewBase.php @@ -78,7 +78,7 @@ abstract class CustomFieldViewBase extends ControllerBase $this->view->assign('field', $customField); $this->view->assign( 'types', - SelectItemAdapter::factory($this->customFieldTypeService->getAllBasic()) + SelectItemAdapter::factory($this->customFieldTypeService->getAll()) ->getItemsFromModelSelected([$customField->getTypeId()]) ); $this->view->assign( diff --git a/app/modules/web/Controllers/Helpers/Account/AccountHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountHelper.php index bbec56d9..2379f937 100644 --- a/app/modules/web/Controllers/Helpers/Account/AccountHelper.php +++ b/app/modules/web/Controllers/Helpers/Account/AccountHelper.php @@ -43,6 +43,7 @@ use SP\Domain\Client\Ports\ClientServiceInterface; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Core\Acl\AccountPermissionException; use SP\Domain\Core\Acl\AclActionsInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Acl\UnauthorizedPageException; use SP\Domain\Core\Exceptions\ConstraintException; use SP\Domain\Core\Exceptions\NoSuchPropertyException; @@ -88,19 +89,19 @@ final class AccountHelper extends AccountHelperBase private TagServiceInterface $tagService; public function __construct( - Application $application, - TemplateInterface $template, - RequestInterface $request, - Acl $acl, - AccountServiceInterface $accountService, + Application $application, + TemplateInterface $template, + RequestInterface $request, + AclInterface $acl, + AccountServiceInterface $accountService, AccountHistoryServiceInterface $accountHistoryService, - PublicLinkServiceInterface $publicLinkService, - ItemPresetServiceInterface $itemPresetService, - MasterPassServiceInterface $masterPassService, - AccountActionsHelper $accountActionsHelper, - AccountAclServiceInterface $accountAclService, - CategoryServiceInterface $categoryService, - ClientServiceInterface $clientService, + PublicLinkServiceInterface $publicLinkService, + ItemPresetServiceInterface $itemPresetService, + MasterPassServiceInterface $masterPassService, + AccountActionsHelper $accountActionsHelper, + AccountAclServiceInterface $accountAclService, + CategoryServiceInterface $categoryService, + ClientServiceInterface $clientService, CustomFieldServiceInterface $customFieldService, UserServiceInterface $userService, UserGroupServiceInterface $userGroupService, @@ -155,9 +156,9 @@ final class AccountHelper extends AccountHelperBase $accountActionsDto = new AccountActionsDto($this->accountId, null, $accountData->getParentId()); - $selectUsers = SelectItemAdapter::factory($this->userService->getAllBasic()); - $selectUserGroups = SelectItemAdapter::factory($this->userGroupService->getAllBasic()); - $selectTags = SelectItemAdapter::factory($this->tagService->getAllBasic()); + $selectUsers = SelectItemAdapter::factory($this->userService->getAll()); + $selectUserGroups = SelectItemAdapter::factory($this->userGroupService->getAll()); + $selectTags = SelectItemAdapter::factory($this->tagService->getAll()); $usersView = SelectItemAdapter::getIdFromArrayOfObjects( array_filter( @@ -337,7 +338,7 @@ final class AccountHelper extends AccountHelperBase $this->view->assign( 'categories', - SelectItemAdapter::factory($this->categoryService->getAllBasic())->getItemsFromModel() + SelectItemAdapter::factory($this->categoryService->getAll())->getItemsFromModel() ); $this->view->assign( 'clients', @@ -422,9 +423,9 @@ final class AccountHelper extends AccountHelperBase $accountPermission = $itemPresetPermission->hydrate(AccountPermission::class) ?: $accountPermission; } - $selectUsers = SelectItemAdapter::factory($this->userService->getAllBasic()); - $selectUserGroups = SelectItemAdapter::factory($this->userGroupService->getAllBasic()); - $selectTags = SelectItemAdapter::factory($this->tagService->getAllBasic()); + $selectUsers = SelectItemAdapter::factory($this->userService->getAll()); + $selectUserGroups = SelectItemAdapter::factory($this->userGroupService->getAll()); + $selectTags = SelectItemAdapter::factory($this->tagService->getAll()); $this->view->assign('accountPassDateChange', date('Y-m-d', time() + 7776000)); $this->view->assign( diff --git a/app/modules/web/Controllers/Helpers/Account/AccountHelperBase.php b/app/modules/web/Controllers/Helpers/Account/AccountHelperBase.php index e82c6ee1..eeabb609 100644 --- a/app/modules/web/Controllers/Helpers/Account/AccountHelperBase.php +++ b/app/modules/web/Controllers/Helpers/Account/AccountHelperBase.php @@ -28,6 +28,7 @@ namespace SP\Modules\Web\Controllers\Helpers\Account; use SP\Core\Acl\Acl; use SP\Core\Application; use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Acl\UnauthorizedPageException; use SP\Domain\Core\Exceptions\SPException; use SP\Domain\Crypt\Ports\MasterPassServiceInterface; @@ -49,10 +50,10 @@ abstract class AccountHelperBase extends HelperBase private MasterPassServiceInterface $masterPassService; public function __construct( - Application $application, - TemplateInterface $template, - RequestInterface $request, - Acl $acl, + Application $application, + TemplateInterface $template, + RequestInterface $request, + AclInterface $acl, AccountActionsHelper $accountActionsHelper, MasterPassServiceInterface $masterPassService ) { diff --git a/app/modules/web/Controllers/Helpers/Account/AccountHistoryHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountHistoryHelper.php index 8a571bae..c50b9a88 100644 --- a/app/modules/web/Controllers/Helpers/Account/AccountHistoryHelper.php +++ b/app/modules/web/Controllers/Helpers/Account/AccountHistoryHelper.php @@ -37,6 +37,7 @@ use SP\Domain\Category\Ports\CategoryServiceInterface; use SP\Domain\Client\Ports\ClientServiceInterface; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Core\Acl\AccountPermissionException; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Acl\UnauthorizedPageException; use SP\Domain\Core\Exceptions\ConstraintException; use SP\Domain\Core\Exceptions\QueryException; @@ -59,17 +60,17 @@ final class AccountHistoryHelper extends AccountHelperBase private ?AccountAcl $accountAcl = null; public function __construct( - Application $application, - TemplateInterface $template, - RequestInterface $request, - Acl $acl, - AccountActionsHelper $accountActionsHelper, - MasterPassServiceInterface $masterPassService, + Application $application, + TemplateInterface $template, + RequestInterface $request, + AclInterface $acl, + AccountActionsHelper $accountActionsHelper, + MasterPassServiceInterface $masterPassService, private AccountHistoryServiceInterface $accountHistoryService, - private AccountAclServiceInterface $accountAclService, - private CategoryServiceInterface $categoryService, - private ClientServiceInterface $clientService, - private AccountToUserServiceInterface $accountToUserService, + private AccountAclServiceInterface $accountAclService, + private CategoryServiceInterface $categoryService, + private ClientServiceInterface $clientService, + private AccountToUserServiceInterface $accountToUserService, private AccountToUserGroupServiceInterface $accountToUserGroupService ) { parent::__construct($application, $template, $request, $acl, $accountActionsHelper, $masterPassService); @@ -116,12 +117,12 @@ final class AccountHistoryHelper extends AccountHelperBase ); $this->view->assign( 'categories', - SelectItemAdapter::factory($this->categoryService->getAllBasic()) + SelectItemAdapter::factory($this->categoryService->getAll()) ->getItemsFromModelSelected([$accountHistoryData->getCategoryId()]) ); $this->view->assign( 'clients', - SelectItemAdapter::factory($this->clientService->getAllBasic()) + SelectItemAdapter::factory($this->clientService->getAll()) ->getItemsFromModelSelected([$accountHistoryData->getClientId()]) ); $this->view->assign( diff --git a/app/modules/web/Controllers/Helpers/Account/AccountPasswordHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountPasswordHelper.php index 514b8307..793bc79b 100644 --- a/app/modules/web/Controllers/Helpers/Account/AccountPasswordHelper.php +++ b/app/modules/web/Controllers/Helpers/Account/AccountPasswordHelper.php @@ -35,6 +35,7 @@ use SP\Core\Crypt\Session as CryptSession; use SP\Domain\Account\Adapters\AccountPassData; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Core\Acl\AclActionsInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Exceptions\FileNotFoundException; use SP\Domain\Crypt\Ports\MasterPassServiceInterface; use SP\Domain\Http\RequestInterface; @@ -57,10 +58,10 @@ final class AccountPasswordHelper extends HelperBase private MasterPassServiceInterface $masterPassService; public function __construct( - Application $application, - TemplateInterface $template, - RequestInterface $request, - Acl $acl, + Application $application, + TemplateInterface $template, + RequestInterface $request, + AclInterface $acl, ImageUtilInterface $imageUtil, MasterPassServiceInterface $masterPassService ) { diff --git a/app/modules/web/Controllers/Helpers/Account/AccountSearchHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountSearchHelper.php index 06287a47..92f60961 100644 --- a/app/modules/web/Controllers/Helpers/Account/AccountSearchHelper.php +++ b/app/modules/web/Controllers/Helpers/Account/AccountSearchHelper.php @@ -181,12 +181,12 @@ final class AccountSearchHelper extends HelperBase ); $this->view->assign( 'categories', - SelectItemAdapter::factory($this->categoryService->getAllBasic()) + SelectItemAdapter::factory($this->categoryService->getAll()) ->getItemsFromModelSelected([$this->accountSearchFilter->getCategoryId()]) ); $this->view->assign( 'tags', - SelectItemAdapter::factory($this->tagService->getAllBasic()) + SelectItemAdapter::factory($this->tagService->getAll()) ->getItemsFromModelSelected($this->accountSearchFilter->getTagsId()) ); } diff --git a/app/modules/web/Controllers/Helpers/Grid/GridBase.php b/app/modules/web/Controllers/Helpers/Grid/GridBase.php index c2f8f112..1b932a72 100644 --- a/app/modules/web/Controllers/Helpers/Grid/GridBase.php +++ b/app/modules/web/Controllers/Helpers/Grid/GridBase.php @@ -28,6 +28,7 @@ use SP\Core\Acl\Acl; use SP\Core\Application; use SP\Core\UI\ThemeIcons; use SP\DataModel\ItemSearchData; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Http\RequestInterface; use SP\Html\DataGrid\Action\DataGridActionSearch; use SP\Html\DataGrid\DataGridData; @@ -52,7 +53,7 @@ abstract class GridBase extends HelperBase implements GridInterface Application $application, TemplateInterface $template, RequestInterface $request, - Acl $acl + AclInterface $acl ) { parent::__construct($application, $template, $request); diff --git a/app/modules/web/Controllers/Helpers/ItemPresetHelper.php b/app/modules/web/Controllers/Helpers/ItemPresetHelper.php index 323c9dc9..01eec970 100644 --- a/app/modules/web/Controllers/Helpers/ItemPresetHelper.php +++ b/app/modules/web/Controllers/Helpers/ItemPresetHelper.php @@ -149,9 +149,9 @@ final class ItemPresetHelper extends HelperBase */ public function setCommon(ItemPreset $itemPresetData): void { - $this->users = SelectItemAdapter::factory($this->userService->getAllBasic()); - $this->userGroups = SelectItemAdapter::factory($this->userGroupService->getAllBasic()); - $userProfiles = SelectItemAdapter::factory($this->userProfileService->getAllBasic()); + $this->users = SelectItemAdapter::factory($this->userService->getAll()); + $this->userGroups = SelectItemAdapter::factory($this->userGroupService->getAll()); + $userProfiles = SelectItemAdapter::factory($this->userProfileService->getAll()); $this->view->assign( 'users', diff --git a/app/modules/web/Controllers/Helpers/LayoutHelper.php b/app/modules/web/Controllers/Helpers/LayoutHelper.php index 6182acb7..dec7343b 100644 --- a/app/modules/web/Controllers/Helpers/LayoutHelper.php +++ b/app/modules/web/Controllers/Helpers/LayoutHelper.php @@ -29,6 +29,7 @@ use SP\Core\Application; use SP\Core\Bootstrap\BootstrapBase; use SP\Core\Language; use SP\Domain\Core\Acl\AclActionsInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\AppInfoInterface; use SP\Domain\Core\Crypt\CryptPKIInterface; use SP\Domain\Core\Exceptions\SPException; @@ -76,11 +77,11 @@ final class LayoutHelper extends HelperBase * Sets a full layout page * * @param string $page Page/view name - * @param Acl|null $acl + * @param AclInterface|null $acl * * @return LayoutHelper */ - public function getFullLayout(string $page, Acl $acl = null): LayoutHelper + public function getFullLayout(string $page, AclInterface $acl = null): LayoutHelper { $this->view->addTemplate('main', '_layouts'); $this->view->assign('useFixedHeader', true); @@ -283,9 +284,9 @@ final class LayoutHelper extends HelperBase /** * Obtener los datos para mostrar el menú de acciones * - * @param Acl $acl + * @param AclInterface $acl */ - public function getMenu(Acl $acl): void + public function getMenu(AclInterface $acl): void { $icons = $this->theme->getIcons(); $actions = []; diff --git a/app/modules/web/Controllers/Items/CategoriesController.php b/app/modules/web/Controllers/Items/CategoriesController.php index d62181c6..122b370c 100644 --- a/app/modules/web/Controllers/Items/CategoriesController.php +++ b/app/modules/web/Controllers/Items/CategoriesController.php @@ -62,7 +62,7 @@ final class CategoriesController extends SimpleControllerBase { JsonResponse::factory($this->router->response()) ->sendRaw( - SelectItemAdapter::factory($this->categoryService->getAllBasic())->getJsonItemsFromModel() + SelectItemAdapter::factory($this->categoryService->getAll())->getJsonItemsFromModel() ); } } diff --git a/app/modules/web/Controllers/Items/TagsController.php b/app/modules/web/Controllers/Items/TagsController.php index 302a240a..61d22268 100644 --- a/app/modules/web/Controllers/Items/TagsController.php +++ b/app/modules/web/Controllers/Items/TagsController.php @@ -61,6 +61,6 @@ final class TagsController extends SimpleControllerBase public function tagsAction(): void { JsonResponse::factory($this->router->response()) - ->sendRaw(SelectItemAdapter::factory($this->tagService->getAllBasic())->getJsonItemsFromModel()); + ->sendRaw(SelectItemAdapter::factory($this->tagService->getAll())->getJsonItemsFromModel()); } } diff --git a/app/modules/web/Controllers/Notification/NotificationViewBase.php b/app/modules/web/Controllers/Notification/NotificationViewBase.php index 6946e27b..3ce6a991 100644 --- a/app/modules/web/Controllers/Notification/NotificationViewBase.php +++ b/app/modules/web/Controllers/Notification/NotificationViewBase.php @@ -82,7 +82,7 @@ abstract class NotificationViewBase extends ControllerBase if ($this->userData->getIsAdminApp()) { $this->view->assign( 'users', - SelectItemAdapter::factory($this->userService->getAllBasic()) + SelectItemAdapter::factory($this->userService->getAll()) ->getItemsFromModelSelected([$notification->userId]) ); } diff --git a/app/modules/web/Controllers/PublicLink/PublicLinkViewBase.php b/app/modules/web/Controllers/PublicLink/PublicLinkViewBase.php index cba011e1..69128854 100644 --- a/app/modules/web/Controllers/PublicLink/PublicLinkViewBase.php +++ b/app/modules/web/Controllers/PublicLink/PublicLinkViewBase.php @@ -28,7 +28,7 @@ namespace SP\Modules\Web\Controllers\PublicLink; use SP\Core\Acl\Acl; use SP\Core\Application; use SP\Core\Bootstrap\BootstrapWeb; -use SP\DataModel\PublicLinkListData; +use SP\DataModel\PublicLinkList; use SP\Domain\Account\Ports\AccountServiceInterface; use SP\Domain\Account\Ports\PublicLinkServiceInterface; use SP\Domain\Account\Services\PublicLinkService; @@ -77,7 +77,7 @@ abstract class PublicLinkViewBase extends ControllerBase $publicLink = $publicLinkId ? $this->publicLinkService->getById($publicLinkId) - : new PublicLinkListData(); + : new PublicLinkList(); $this->view->assign('publicLink', $publicLink); $this->view->assign('usageInfo', unserialize($publicLink->getUseInfo(), ['allowed_classes' => false])); diff --git a/app/modules/web/Controllers/PublicLink/SaveCreateFromAccountController.php b/app/modules/web/Controllers/PublicLink/SaveCreateFromAccountController.php index f76c8ec8..2a112000 100644 --- a/app/modules/web/Controllers/PublicLink/SaveCreateFromAccountController.php +++ b/app/modules/web/Controllers/PublicLink/SaveCreateFromAccountController.php @@ -27,7 +27,7 @@ namespace SP\Modules\Web\Controllers\PublicLink; use Exception; use JsonException; use SP\Core\Events\Event; -use SP\DataModel\PublicLinkData; +use SP\Domain\Account\Models\PublicLink; use SP\Domain\Account\Services\PublicLinkService; use SP\Domain\Core\Acl\AclActionsInterface; use SP\Http\JsonMessage; @@ -44,8 +44,8 @@ final class SaveCreateFromAccountController extends PublicLinkSaveBase /** * Saves create action * - * @param int $accountId - * @param int $notify + * @param int $accountId + * @param int $notify * * @return bool * @throws JsonException @@ -60,11 +60,14 @@ final class SaveCreateFromAccountController extends PublicLinkSaveBase ); } - $publicLinkData = new PublicLinkData(); - $publicLinkData->setTypeId(PublicLinkService::TYPE_ACCOUNT); - $publicLinkData->setItemId($accountId); - $publicLinkData->setNotify((bool)$notify); - $publicLinkData->setHash(PasswordUtil::generateRandomBytes()); + $publicLinkData = new PublicLink( + [ + 'id' => PublicLinkService::TYPE_ACCOUNT, + 'itemId' => $accountId, + 'notify' => (bool)$notify, + 'hash' => PasswordUtil::generateRandomBytes() + ] + ); $this->publicLinkService->create($publicLinkData); diff --git a/app/modules/web/Controllers/User/UserViewBase.php b/app/modules/web/Controllers/User/UserViewBase.php index 6bd5753a..d9cfbcdf 100644 --- a/app/modules/web/Controllers/User/UserViewBase.php +++ b/app/modules/web/Controllers/User/UserViewBase.php @@ -93,11 +93,11 @@ abstract class UserViewBase extends ControllerBase $this->view->assign('user', $user); $this->view->assign( 'groups', - SelectItemAdapter::factory($this->userGroupService->getAllBasic())->getItemsFromModel() + SelectItemAdapter::factory($this->userGroupService->getAll())->getItemsFromModel() ); $this->view->assign( 'profiles', - SelectItemAdapter::factory($this->userProfileService->getAllBasic())->getItemsFromModel() + SelectItemAdapter::factory($this->userProfileService->getAll())->getItemsFromModel() ); $this->view->assign('isUseSSO', $this->configData->isAuthBasicAutoLoginEnabled()); $this->view->assign( diff --git a/app/modules/web/Controllers/UserGroup/UserGroupViewBase.php b/app/modules/web/Controllers/UserGroup/UserGroupViewBase.php index 5eae7ebb..aaeee530 100644 --- a/app/modules/web/Controllers/UserGroup/UserGroupViewBase.php +++ b/app/modules/web/Controllers/UserGroup/UserGroupViewBase.php @@ -94,7 +94,7 @@ abstract class UserGroupViewBase extends ControllerBase $this->view->assign( 'users', - SelectItemAdapter::factory($this->userService->getAllBasic())->getItemsFromModelSelected($users) + SelectItemAdapter::factory($this->userService->getAll())->getItemsFromModelSelected($users) ); $this->view->assign( 'usedBy', diff --git a/app/modules/web/Forms/AuthTokenForm.php b/app/modules/web/Forms/AuthTokenForm.php index 6fdcc2e0..2748fa54 100644 --- a/app/modules/web/Forms/AuthTokenForm.php +++ b/app/modules/web/Forms/AuthTokenForm.php @@ -24,8 +24,8 @@ namespace SP\Modules\Web\Forms; -use SP\DataModel\AuthToken; -use SP\Domain\Auth\Services\AuthTokenService; +use SP\Domain\Auth\Models\AuthToken; +use SP\Domain\Auth\Services\AuthToken; use SP\Domain\Core\Acl\AclActionsInterface; use SP\Domain\Core\Exceptions\ValidationException; @@ -95,7 +95,7 @@ final class AuthTokenForm extends FormBase implements FormInterface } if (empty($this->authTokenData->getHash()) - && (AuthTokenService::isSecuredAction($this->authTokenData->getActionId()) + && (AuthToken::isSecuredAction($this->authTokenData->getActionId()) || $this->isRefresh())) { throw new ValidationException(__u('Password cannot be blank')); } diff --git a/app/modules/web/Forms/PublicLinkForm.php b/app/modules/web/Forms/PublicLinkForm.php index de3f03b7..99f8aaf8 100644 --- a/app/modules/web/Forms/PublicLinkForm.php +++ b/app/modules/web/Forms/PublicLinkForm.php @@ -24,7 +24,7 @@ namespace SP\Modules\Web\Forms; -use SP\DataModel\PublicLinkData; +use SP\Domain\Account\Models\PublicLink; use SP\Domain\Account\Services\PublicLinkService; use SP\Domain\Core\Acl\AclActionsInterface; use SP\Domain\Core\Exceptions\ValidationException; @@ -36,13 +36,13 @@ use SP\Domain\Core\Exceptions\ValidationException; */ final class PublicLinkForm extends FormBase implements FormInterface { - protected ?PublicLinkData $publicLinkData = null; + protected ?PublicLink $publicLink = null; /** * Validar el formulario * - * @param int $action - * @param int|null $id + * @param int $action + * @param int|null $id * * @return PublicLinkForm * @throws ValidationException @@ -71,11 +71,14 @@ final class PublicLinkForm extends FormBase implements FormInterface */ protected function analyzeRequestData(): void { - $this->publicLinkData = new PublicLinkData(); - $this->publicLinkData->setId($this->itemId); - $this->publicLinkData->setTypeId(PublicLinkService::TYPE_ACCOUNT); - $this->publicLinkData->setItemId($this->request->analyzeInt('accountId')); - $this->publicLinkData->setNotify($this->request->analyzeBool('notify', false)); + $this->publicLink = new PublicLink( + [ + 'id' => $this->itemId, + 'typeId' => PublicLinkService::TYPE_ACCOUNT, + 'itemId' => $this->request->analyzeInt('accountId'), + 'notify' => $this->request->analyzeBool('notify', false) + ] + ); } /** @@ -83,13 +86,13 @@ final class PublicLinkForm extends FormBase implements FormInterface */ protected function checkCommon(): void { - if (!$this->publicLinkData->getItemId()) { + if (!$this->publicLink->getItemId()) { throw new ValidationException(__u('An account is needed')); } } - public function getItemData(): ?PublicLinkData + public function getItemData(): ?PublicLink { - return $this->publicLinkData; + return $this->publicLink; } } diff --git a/app/modules/web/themes/material-blue/views/itemshow/auth_token.inc b/app/modules/web/themes/material-blue/views/itemshow/auth_token.inc index 854975eb..5562a3a3 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/auth_token.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/auth_token.inc @@ -30,7 +30,7 @@ * @var TemplateInterface $this */ -use SP\DataModel\AuthToken; +use SP\Domain\Auth\Models\AuthToken; use SP\Domain\Config\Ports\ConfigDataInterface; use SP\Domain\Core\UI\ThemeIconsInterface; use SP\Mvc\View\Components\SelectItem; diff --git a/app/modules/web/themes/material-blue/views/itemshow/public_link.inc b/app/modules/web/themes/material-blue/views/itemshow/public_link.inc index 339fd486..2e25e0f0 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/public_link.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/public_link.inc @@ -23,14 +23,14 @@ */ /** - * @var PublicLinkListData $publicLink + * @var PublicLinkList $publicLink * @var ThemeIconsInterface $icons * @var ConfigDataInterface $configData * @var callable $_getvar * @var TemplateInterface $this */ -use SP\DataModel\PublicLinkListData; +use SP\DataModel\PublicLinkList; use SP\Domain\Config\Ports\ConfigDataInterface; use SP\Domain\Core\UI\ThemeIconsInterface; use SP\Mvc\View\Components\SelectItem; diff --git a/lib/SP/Core/Acl/Acl.php b/lib/SP/Core/Acl/Acl.php index a730bfc7..3388a388 100644 --- a/lib/SP/Core/Acl/Acl.php +++ b/lib/SP/Core/Acl/Acl.php @@ -28,6 +28,7 @@ namespace SP\Core\Acl; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Domain\Core\Acl\AclActionsInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Acl\ActionNotFoundException; use SP\Domain\Core\Acl\ActionsInterface; use SP\Domain\Core\Context\ContextInterface; @@ -40,25 +41,55 @@ use function SP\processException; /** * Esta clase es la encargada de calcular las access lists de acceso a usuarios. */ -final class Acl implements AclActionsInterface +final class Acl implements AclActionsInterface, AclInterface { - private static ActionsInterface $actions; + /** + * @deprecated + */ + private static ActionsInterface $actionsStatic; + private ActionsInterface $actions; public function __construct( private readonly ContextInterface $context, private readonly EventDispatcherInterface $eventDispatcher, ActionsInterface $actions ) { - self::$actions = $actions; + self::$actionsStatic = $actions; + $this->actions = $actions; } /** * Returns action route + * + * @deprecated Use {@link Acl::getRouteFor()} instead */ public static function getActionRoute(string $actionId): string { try { - return self::$actions?->getActionById($actionId)->getRoute(); + return self::$actionsStatic?->getActionById($actionId)->getRoute(); + } catch (ActionNotFoundException $e) { + processException($e); + } + + return ''; + } + + /** + * Obtener el nombre de la acción indicada + * + * @param int $actionId El id de la acción + * @param bool $translate + * + * @return string + * @internal param bool $translate Si se devuelve el nombre corto de la acción + * @deprecated Use {@link Acl::getInfoFor()} instead + */ + public static function getActionInfo(int $actionId, bool $translate = true): string + { + try { + $text = self::$actionsStatic?->getActionById($actionId)->getText(); + + return $translate ? __($text) : $text; } catch (ActionNotFoundException $e) { processException($e); } @@ -75,10 +106,10 @@ final class Acl implements AclActionsInterface * @return string * @internal param bool $translate Si se devuelve el nombre corto de la acción */ - public static function getActionInfo(int $actionId, bool $translate = true): string + public function getInfoFor(int $actionId, bool $translate = true): string { try { - $text = self::$actions?->getActionById($actionId)->getText(); + $text = $this->actions->getActionById($actionId)->getText(); return $translate ? __($text) : $text; } catch (ActionNotFoundException $e) { @@ -88,6 +119,20 @@ final class Acl implements AclActionsInterface return ''; } + /** + * Returns action route + */ + public function getRouteFor(string $actionId): string + { + try { + return $this->actions->getActionById($actionId)->getRoute(); + } catch (ActionNotFoundException $e) { + processException($e); + } + + return ''; + } + /** * Comprobar los permisos de acceso del usuario a los módulos de la aplicación. */ @@ -267,8 +312,8 @@ final class Acl implements AclActionsInterface } try { - $actionName = self::$actions->getActionById($action)->getName(); - } catch (ActionNotFoundException $e) { + $actionName = $this->actions->getActionById($action)->getName(); + } catch (ActionNotFoundException) { $actionName = __u('N/A'); } diff --git a/lib/SP/DataModel/AccountExtData.php b/lib/SP/DataModel/AccountExtData.php deleted file mode 100644 index 7915533b..00000000 --- a/lib/SP/DataModel/AccountExtData.php +++ /dev/null @@ -1,78 +0,0 @@ -. - */ - -namespace SP\DataModel; - -use SP\Domain\Account\Adapters\AccountData; - -/** - * Class AccountExtData - * - * @package SP\DataModel - */ -class AccountExtData extends AccountData -{ - 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; - - public function getUserEditName(): ?string - { - return $this->userEditName; - } - - public function getUserEditLogin(): ?string - { - return $this->userEditLogin; - } - - 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; - } -} diff --git a/lib/SP/DataModel/ItemSearchData.php b/lib/SP/DataModel/ItemSearchData.php index fb448d8c..bd323187 100644 --- a/lib/SP/DataModel/ItemSearchData.php +++ b/lib/SP/DataModel/ItemSearchData.php @@ -28,20 +28,13 @@ use SP\Util\Filter; /** * Class ItemSearchData - * - * @package SP\DataModel */ class ItemSearchData { - /** - * @param string|null $seachString - * @param int|null $limitStart - * @param int|null $limitCount - */ public function __construct( - private ?string $seachString = null, - private ?int $limitStart = 0, - private ?int $limitCount = 0, + private ?string $seachString = null, + private readonly ?int $limitStart = 0, + private readonly ?int $limitCount = 0, ) { if (!empty($seachString)) { $this->seachString = Filter::safeSearchString($seachString); diff --git a/lib/SP/DataModel/PublicLinkListData.php b/lib/SP/DataModel/PublicLinkList.php similarity index 94% rename from lib/SP/DataModel/PublicLinkListData.php rename to lib/SP/DataModel/PublicLinkList.php index 2d8de7d2..10c5b5af 100644 --- a/lib/SP/DataModel/PublicLinkListData.php +++ b/lib/SP/DataModel/PublicLinkList.php @@ -24,12 +24,14 @@ namespace SP\DataModel; +use SP\Domain\Account\Models\PublicLink; + /** * Class PublicLinkListData * * @package SP\DataModel */ -class PublicLinkListData extends PublicLinkData +class PublicLinkList extends PublicLink { protected ?string $userName = null; protected ?string $userLogin = null; diff --git a/lib/SP/Domain/Account/Adapters/AccountData.php b/lib/SP/Domain/Account/Adapters/AccountData.php deleted file mode 100644 index 9b25ef7e..00000000 --- a/lib/SP/Domain/Account/Adapters/AccountData.php +++ /dev/null @@ -1,183 +0,0 @@ -. - */ - -namespace SP\Domain\Account\Adapters; - -use SP\Domain\Common\Adapters\DataModelInterface; -use SP\Domain\Common\Models\Model; - -/** - * Class AccountData - */ -class AccountData extends Model implements DataModelInterface -{ - 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 = 0; - protected ?int $dateEdit = 0; - protected ?int $countView = 0; - protected ?int $countDecrypt = 0; - protected ?int $isPrivate = 0; - protected ?int $isPrivateGroup = 0; - protected ?int $passDate = 0; - protected ?int $passDateChange = 0; - protected ?int $parentId = 0; - protected ?bool $otherUserGroupEdit = false; - protected ?bool $otherUserEdit = false; - - public function getDateAdd(): ?int - { - return $this->dateAdd; - } - - public function getDateEdit(): ?int - { - return $this->dateEdit; - } - - public function getUserEditId(): ?int - { - return $this->userEditId; - } - - public function getPass(): ?string - { - return $this->pass; - } - - public function setPass(string $pass): void - { - $this->pass = $pass; - } - - public function getKey(): ?string - { - return $this->key; - } - - public function setKey(string $key): void - { - $this->key = $key; - } - - public function getId(): ?int - { - return $this->id; - } - - public function getUserId(): ?int - { - return $this->userId; - } - - public function getUserGroupId(): ?int - { - return $this->userGroupId; - } - - public function getName(): ?string - { - return $this->name; - } - - public function getCategoryId(): ?int - { - return $this->categoryId; - } - - 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 getCountView(): ?int - { - return $this->countView; - } - - public function getCountDecrypt(): ?int - { - return $this->countDecrypt; - } - - public function getIsPrivate(): ?int - { - return $this->isPrivate; - } - - public function getPassDate(): ?int - { - return $this->passDate; - } - - public function getPassDateChange(): ?int - { - return $this->passDateChange; - } - - public function getParentId(): ?int - { - return $this->parentId; - } - - public function getIsPrivateGroup(): ?int - { - return $this->isPrivateGroup; - } - - public function getOtherUserGroupEdit(): ?bool - { - return $this->otherUserGroupEdit; - } - - public function getOtherUserEdit(): ?bool - { - return $this->otherUserEdit; - } -} diff --git a/lib/SP/Domain/Account/Dtos/AccountAclDto.php b/lib/SP/Domain/Account/Dtos/AccountAclDto.php index 3126f047..14771447 100644 --- a/lib/SP/Domain/Account/Dtos/AccountAclDto.php +++ b/lib/SP/Domain/Account/Dtos/AccountAclDto.php @@ -24,7 +24,6 @@ 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; @@ -38,28 +37,20 @@ final class AccountAclDto { use ItemDataTrait; - /** - * @param int $accountId - * @param int $userId - * @param ItemData[] $usersId - * @param int $userGroupId - * @param ItemData[] $userGroupsId - * @param int $dateEdit - */ public function __construct( - private int $accountId, - private int $userId, - private array $usersId, - private int $userGroupId, - private array $userGroupsId, - private int $dateEdit + private readonly int $accountId, + private readonly int $userId, + private array $usersId, + private readonly int $userGroupId, + private array $userGroupsId, + private readonly int $dateEdit ) { $this->usersId = self::buildFromItemData($usersId); $this->userGroupsId = self::buildFromItemData($userGroupsId); } /** - * @param AccountEnrichedDto $accountDetailsResponse + * @param AccountEnrichedDto $accountDetailsResponse * * @return AccountAclDto */ @@ -91,10 +82,10 @@ final class AccountAclDto } /** - * @param AccountSearchView $accountSearchView + * @param AccountSearchView $accountSearchView * - * @param array $users - * @param array $userGroups + * @param array $users + * @param array $userGroups * * @return AccountAclDto */ diff --git a/lib/SP/Domain/Account/Dtos/AccountCacheDto.php b/lib/SP/Domain/Account/Dtos/AccountCacheDto.php index c1397679..56c09cea 100644 --- a/lib/SP/Domain/Account/Dtos/AccountCacheDto.php +++ b/lib/SP/Domain/Account/Dtos/AccountCacheDto.php @@ -31,17 +31,20 @@ namespace SP\Domain\Account\Dtos; */ class AccountCacheDto { - private int $time; + private readonly int $time; /** * AccountCacheDto constructor. * - * @param int $accountId - * @param array $users - * @param array $userGroups + * @param int $accountId + * @param array $users + * @param array $userGroups */ - public function __construct(private int $accountId, private array $users, private array $userGroups) - { + public function __construct( + private readonly int $accountId, + private readonly array $users, + private readonly array $userGroups + ) { $this->time = time(); } diff --git a/lib/SP/Domain/Account/Dtos/AccountEnrichedDto.php b/lib/SP/Domain/Account/Dtos/AccountEnrichedDto.php index d7a1832f..b405a2c9 100644 --- a/lib/SP/Domain/Account/Dtos/AccountEnrichedDto.php +++ b/lib/SP/Domain/Account/Dtos/AccountEnrichedDto.php @@ -25,8 +25,7 @@ namespace SP\Domain\Account\Dtos; use SP\DataModel\ItemData; -use SP\Domain\Account\Models\AccountDataView; -use SP\Domain\Account\Models\AccountSearchView; +use SP\Domain\Account\Models\AccountView; use SP\Domain\Common\Dtos\ItemDataTrait; /** @@ -36,7 +35,7 @@ class AccountEnrichedDto { use ItemDataTrait; - private int $id; + private readonly int $id; /** * @var ItemData[] Los usuarios secundarios de la cuenta. */ @@ -53,9 +52,9 @@ class AccountEnrichedDto /** * AccountDetailsResponse constructor. * - * @param \SP\Domain\Account\Models\AccountDataView $accountDataView + * @param AccountView $accountDataView */ - public function __construct(private AccountDataView $accountDataView) + public function __construct(private readonly AccountView $accountDataView) { $this->id = $accountDataView->getId(); } @@ -69,9 +68,9 @@ class AccountEnrichedDto } /** - * @param ItemData[] $users + * @param ItemData[] $users * - * @return \SP\Domain\Account\Dtos\AccountEnrichedDto + * @return AccountEnrichedDto */ public function withUsers(array $users): AccountEnrichedDto { @@ -82,9 +81,9 @@ class AccountEnrichedDto } /** - * @param ItemData[] $groups + * @param ItemData[] $groups * - * @return \SP\Domain\Account\Dtos\AccountEnrichedDto + * @return AccountEnrichedDto */ public function withUserGroups(array $groups): AccountEnrichedDto { @@ -95,9 +94,9 @@ class AccountEnrichedDto } /** - * @param ItemData[] $tags + * @param ItemData[] $tags * - * @return \SP\Domain\Account\Dtos\AccountEnrichedDto + * @return AccountEnrichedDto */ public function withTags(array $tags): AccountEnrichedDto { @@ -131,7 +130,7 @@ class AccountEnrichedDto return $this->tags; } - public function getAccountDataView(): AccountDataView + public function getAccountDataView(): AccountView { return $this->accountDataView; } diff --git a/lib/SP/Domain/Account/Dtos/AccountHistoryCreateDto.php b/lib/SP/Domain/Account/Dtos/AccountHistoryCreateDto.php index 0735bde3..1c0ec1b5 100644 --- a/lib/SP/Domain/Account/Dtos/AccountHistoryCreateDto.php +++ b/lib/SP/Domain/Account/Dtos/AccountHistoryCreateDto.php @@ -32,11 +32,12 @@ use SP\Domain\Account\Models\Account; class AccountHistoryCreateDto { public function __construct( - private Account $account, - private bool $isModify, - private bool $isDelete, - private string $masterPassHash - ) {} + private readonly Account $account, + private readonly bool $isModify, + private readonly bool $isDelete, + private readonly string $masterPassHash + ) { + } public function isModify(): bool { diff --git a/lib/SP/Domain/Account/Dtos/AccountPasswordRequest.php b/lib/SP/Domain/Account/Dtos/AccountPasswordRequest.php index ae121737..fa1a5d9e 100644 --- a/lib/SP/Domain/Account/Dtos/AccountPasswordRequest.php +++ b/lib/SP/Domain/Account/Dtos/AccountPasswordRequest.php @@ -30,10 +30,11 @@ namespace SP\Domain\Account\Dtos; final class AccountPasswordRequest { public function __construct( - private int $id, - private EncryptedPassword $encryptedPassword, - private ?string $hash = null - ) {} + private readonly int $id, + private readonly EncryptedPassword $encryptedPassword, + private readonly ?string $hash = null + ) { + } public function getId(): int { diff --git a/lib/SP/Domain/Account/Dtos/AccountUpdateBulkDto.php b/lib/SP/Domain/Account/Dtos/AccountUpdateBulkDto.php index c3f7f24b..fc575eb7 100644 --- a/lib/SP/Domain/Account/Dtos/AccountUpdateBulkDto.php +++ b/lib/SP/Domain/Account/Dtos/AccountUpdateBulkDto.php @@ -43,7 +43,7 @@ final class AccountUpdateBulkDto } /** - * @return \SP\Domain\Account\Dtos\AccountUpdateDto[] + * @return AccountUpdateDto[] */ public function getAccountUpdateDto(): array { diff --git a/lib/SP/Domain/Account/Dtos/EncryptedPassword.php b/lib/SP/Domain/Account/Dtos/EncryptedPassword.php index 95782491..66ecfd55 100644 --- a/lib/SP/Domain/Account/Dtos/EncryptedPassword.php +++ b/lib/SP/Domain/Account/Dtos/EncryptedPassword.php @@ -29,7 +29,12 @@ namespace SP\Domain\Account\Dtos; */ final class EncryptedPassword { - public function __construct(private string $pass, private string $key, private ?string $hash = null) {} + public function __construct( + private readonly string $pass, + private readonly string $key, + private readonly ?string $hash = null + ) { + } public function getPass(): string { diff --git a/lib/SP/Domain/Account/Models/AccountUseCases.php b/lib/SP/Domain/Account/Models/AccountUseCases.php index 910a30de..959f4b62 100644 --- a/lib/SP/Domain/Account/Models/AccountUseCases.php +++ b/lib/SP/Domain/Account/Models/AccountUseCases.php @@ -44,8 +44,8 @@ trait AccountUseCases } /** - * @param \SP\Domain\Account\Dtos\AccountCreateDto $accountDto - * @param \SP\Domain\Account\Models\Account $account + * @param AccountCreateDto $accountDto + * @param Account $account * * @return void */ diff --git a/lib/SP/Domain/Account/Models/AccountDataView.php b/lib/SP/Domain/Account/Models/AccountView.php similarity index 99% rename from lib/SP/Domain/Account/Models/AccountDataView.php rename to lib/SP/Domain/Account/Models/AccountView.php index ef5a562f..ea682057 100644 --- a/lib/SP/Domain/Account/Models/AccountDataView.php +++ b/lib/SP/Domain/Account/Models/AccountView.php @@ -29,7 +29,7 @@ use SP\Domain\Common\Models\Model; /** * Class AccountDataView */ -final class AccountDataView extends Model +final class AccountView extends Model { protected ?int $id = null; protected ?string $name = null; diff --git a/lib/SP/DataModel/PublicLinkData.php b/lib/SP/Domain/Account/Models/PublicLink.php similarity index 66% rename from lib/SP/DataModel/PublicLinkData.php rename to lib/SP/Domain/Account/Models/PublicLink.php index cab8dc86..07cc71b7 100644 --- a/lib/SP/DataModel/PublicLinkData.php +++ b/lib/SP/Domain/Account/Models/PublicLink.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2023, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,17 +22,15 @@ * along with sysPass. If not, see . */ -namespace SP\DataModel; +namespace SP\Domain\Account\Models; use SP\Domain\Common\Adapters\DataModelInterface; use SP\Domain\Common\Models\Model; /** - * Class PublicLinkData - * - * @package SP\DataModel + * Class PublicLink */ -class PublicLinkData extends Model implements DataModelInterface +class PublicLink extends Model implements DataModelInterface { protected ?int $id = null; protected ?int $itemId = null; @@ -54,11 +52,6 @@ class PublicLinkData extends Model implements DataModelInterface return $this->data; } - public function setData(?string $data): void - { - $this->data = $data; - } - public function getId(): ?int { return (int)$this->id; @@ -69,106 +62,51 @@ class PublicLinkData extends Model implements DataModelInterface return $this->hash; } - public function setHash(?string $hash): void - { - $this->hash = $hash; - } - public function getItemId(): int { return (int)$this->itemId; } - public function setItemId(int $itemId): void - { - $this->itemId = $itemId; - } - public function getUserId(): int { return (int)$this->userId; } - public function setUserId(int $userId): void - { - $this->userId = $userId; - } - public function getTypeId(): ?int { return $this->typeId; } - public function setTypeId(int $typeId): void - { - $this->typeId = $typeId; - } - public function isNotify(): bool { return $this->notify; } - public function setNotify(bool $notify): void - { - $this->notify = $notify; - } - public function getDateAdd(): ?int { return $this->dateAdd; } - public function setDateAdd(int $dateAdd): void - { - $this->dateAdd = $dateAdd; - } - public function getDateExpire(): ?int { return $this->dateExpire; } - public function setDateExpire(int $dateExpire): void - { - $this->dateExpire = $dateExpire; - } - public function getCountViews(): ?int { return $this->countViews; } - public function setCountViews(int $countViews): void - { - $this->countViews = $countViews; - } - - public function addCountViews(): ?int - { - return $this->countViews++; - } - public function getMaxCountViews(): ?int { return $this->maxCountViews; } - public function setMaxCountViews(int $maxCountViews): void - { - $this->maxCountViews = $maxCountViews; - } - public function getUseInfo(): ?string { return $this->useInfo; } - public function setUseInfo(array $useInfo): void - { - $this->useInfo = serialize($useInfo); - } - public function getTotalCountViews(): ?int { return $this->totalCountViews; diff --git a/lib/SP/Domain/Account/Ports/AccountServiceInterface.php b/lib/SP/Domain/Account/Ports/AccountServiceInterface.php index b428f835..eb521f58 100644 --- a/lib/SP/Domain/Account/Ports/AccountServiceInterface.php +++ b/lib/SP/Domain/Account/Ports/AccountServiceInterface.php @@ -25,7 +25,6 @@ namespace SP\Domain\Account\Ports; use SP\DataModel\ItemSearchData; -use SP\Domain\Account\Adapters\AccountData; use SP\Domain\Account\Dtos\AccountCreateDto; use SP\Domain\Account\Dtos\AccountEnrichedDto; use SP\Domain\Account\Dtos\AccountHistoryDto; @@ -33,7 +32,7 @@ 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\Models\AccountView; use SP\Domain\Common\Models\Simple; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Core\Exceptions\ConstraintException; @@ -78,7 +77,7 @@ interface AccountServiceInterface public function withTags(AccountEnrichedDto $accountEnrichedDto): AccountEnrichedDto; /** - * @param int $id The account ID + * @param int $id The account ID * * @return bool * @throws ConstraintException @@ -87,7 +86,7 @@ interface AccountServiceInterface public function incrementViewCounter(int $id): bool; /** - * @param int $id The account ID + * @param int $id The account ID * * @return bool * @throws QueryException @@ -96,7 +95,7 @@ interface AccountServiceInterface public function incrementDecryptCounter(int $id): bool; /** - * @param int $id The account ID + * @param int $id The account ID * * @return Account * @throws ConstraintException @@ -126,17 +125,17 @@ interface AccountServiceInterface public function create(AccountCreateDto $accountCreateDto): int; /** - * @param int $id The account ID + * @param int $id The account ID * - * @return AccountDataView + * @return AccountView * @throws QueryException * @throws NoSuchItemException * @throws ConstraintException */ - public function getByIdEnriched(int $id): AccountDataView; + public function getByIdEnriched(int $id): AccountView; /** - * @param int $id The account ID + * @param int $id The account ID * * @return Account * @throws NoSuchItemException @@ -146,7 +145,7 @@ interface AccountServiceInterface /** * Updates external items for the account * - * @param int $id The account ID + * @param int $id The account ID * @param AccountUpdateDto $accountUpdateDto * * @throws ServiceException @@ -163,7 +162,7 @@ interface AccountServiceInterface public function updateBulk(AccountUpdateBulkDto $accountUpdateBulkDto): void; /** - * @param int $id The account ID + * @param int $id The account ID * @param AccountUpdateDto $accountUpdateDto * * @throws ServiceException @@ -187,7 +186,7 @@ interface AccountServiceInterface public function restoreModified(AccountHistoryDto $accountHistoryDto): void; /** - * @param int $id The account ID + * @param int $id The account ID * * @return AccountServiceInterface * @throws ServiceException @@ -195,7 +194,7 @@ interface AccountServiceInterface public function delete(int $id): AccountServiceInterface; /** - * @param int[] $ids The accounts ID + * @param int[] $ids The accounts ID * * @throws SPException * @throws ServiceException @@ -203,7 +202,7 @@ interface AccountServiceInterface public function deleteByIdBatch(array $ids): void; /** - * @param int|null $id The account ID + * @param int|null $id The account ID * * @return array * @throws QueryException @@ -212,7 +211,7 @@ interface AccountServiceInterface public function getForUser(?int $id = null): array; /** - * @param int $id The account ID + * @param int $id The account ID * * @return array * @throws QueryException @@ -221,7 +220,7 @@ interface AccountServiceInterface public function getLinked(int $id): array; /** - * @param int $id The account ID + * @param int $id The account ID * * @return Simple * @throws QueryException @@ -231,7 +230,7 @@ interface AccountServiceInterface public function getPasswordHistoryForId(int $id): Simple; /** - * @return AccountData[] + * @return Account[] */ public function getAllBasic(): array; @@ -253,7 +252,7 @@ interface AccountServiceInterface /** * Obtener los datos de una cuenta. * - * @param int $id The account ID + * @param int $id The account ID * * @return Simple * @throws ConstraintException diff --git a/lib/SP/Domain/Account/Ports/PublicLinkRepositoryInterface.php b/lib/SP/Domain/Account/Ports/PublicLinkRepositoryInterface.php index 83adaa32..4f371eac 100644 --- a/lib/SP/Domain/Account/Ports/PublicLinkRepositoryInterface.php +++ b/lib/SP/Domain/Account/Ports/PublicLinkRepositoryInterface.php @@ -25,7 +25,7 @@ namespace SP\Domain\Account\Ports; use SP\DataModel\ItemSearchData; -use SP\DataModel\PublicLinkData; +use SP\Domain\Account\Models\PublicLink; use SP\Domain\Common\Ports\RepositoryInterface; use SP\Domain\Core\Exceptions\ConstraintException; use SP\Domain\Core\Exceptions\QueryException; @@ -81,48 +81,48 @@ interface PublicLinkRepositoryInterface extends RepositoryInterface /** * Creates an item * - * @param PublicLinkData $publicLinkData + * @param \SP\Domain\Account\Models\PublicLink $publicLinkData * * @return QueryResult * @throws DuplicatedItemException * @throws QueryException * @throws ConstraintException */ - public function create(PublicLinkData $publicLinkData): QueryResult; + public function create(PublicLink $publicLinkData): QueryResult; /** * Incrementar el contador de visitas de un enlace * - * @param PublicLinkData $publicLinkData + * @param \SP\Domain\Account\Models\PublicLink $publicLinkData * * @return bool * @throws ConstraintException * @throws QueryException */ - public function addLinkView(PublicLinkData $publicLinkData): bool; + public function addLinkView(PublicLink $publicLinkData): bool; /** * Updates an item * - * @param PublicLinkData $publicLinkData + * @param \SP\Domain\Account\Models\PublicLink $publicLinkData * * @return bool * @throws ConstraintException * @throws QueryException */ - public function update(PublicLinkData $publicLinkData): bool; + public function update(PublicLink $publicLinkData): bool; /** * Refreshes a public link * - * @param PublicLinkData $publicLinkData + * @param \SP\Domain\Account\Models\PublicLink $publicLinkData * * @return bool * @throws SPException * @throws ConstraintException * @throws QueryException */ - public function refresh(PublicLinkData $publicLinkData): bool; + public function refresh(PublicLink $publicLinkData): bool; /** * Returns the item for given id diff --git a/lib/SP/Domain/Account/Ports/PublicLinkServiceInterface.php b/lib/SP/Domain/Account/Ports/PublicLinkServiceInterface.php index 58403f0c..d084d367 100644 --- a/lib/SP/Domain/Account/Ports/PublicLinkServiceInterface.php +++ b/lib/SP/Domain/Account/Ports/PublicLinkServiceInterface.php @@ -27,8 +27,8 @@ namespace SP\Domain\Account\Ports; use Defuse\Crypto\Exception\CryptoException; use Defuse\Crypto\Exception\EnvironmentIsBrokenException; use SP\DataModel\ItemSearchData; -use SP\DataModel\PublicLinkData; -use SP\DataModel\PublicLinkListData; +use SP\DataModel\PublicLinkList; +use SP\Domain\Account\Models\PublicLink; use SP\Domain\Account\Services\PublicLinkKey; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Core\Exceptions\ConstraintException; @@ -55,7 +55,7 @@ interface PublicLinkServiceInterface * @throws QueryException * @throws NoSuchItemException */ - public function getById(int $id): PublicLinkListData; + public function getById(int $id): PublicLinkList; /** * @throws CryptoException @@ -97,16 +97,16 @@ interface PublicLinkServiceInterface * @throws ConstraintException * @throws QueryException */ - public function create(PublicLinkData $itemData): int; + public function create(PublicLink $itemData): int; /** * Get all items from the service's repository * - * @return PublicLinkListData[] + * @return PublicLinkList[] * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array; + public function getAll(): array; /** * Incrementar el contador de visitas de un enlace @@ -115,12 +115,12 @@ interface PublicLinkServiceInterface * @throws ConstraintException * @throws QueryException */ - public function addLinkView(PublicLinkData $publicLinkData): void; + public function addLinkView(PublicLink $publicLink): void; /** * @throws SPException */ - public function getByHash(string $hash): PublicLinkData; + public function getByHash(string $hash): PublicLink; /** * Devolver el hash asociado a un elemento @@ -129,7 +129,7 @@ interface PublicLinkServiceInterface * @throws QueryException * @throws NoSuchItemException */ - public function getHashForItem(int $itemId): PublicLinkData; + public function getHashForItem(int $itemId): PublicLink; /** * Updates an item @@ -138,5 +138,5 @@ interface PublicLinkServiceInterface * @throws ConstraintException * @throws QueryException */ - public function update(PublicLinkData $itemData): void; + public function update(PublicLink $itemData): void; } diff --git a/lib/SP/Domain/Account/Services/AccountAclService.php b/lib/SP/Domain/Account/Services/AccountAclService.php index df4bc7fc..a6f62fa9 100644 --- a/lib/SP/Domain/Account/Services/AccountAclService.php +++ b/lib/SP/Domain/Account/Services/AccountAclService.php @@ -33,6 +33,7 @@ use SP\Domain\Account\Dtos\AccountAclDto; use SP\Domain\Account\Ports\AccountAclServiceInterface; use SP\Domain\Common\Services\Service; use SP\Domain\Core\Acl\AclActionsInterface; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\Exceptions\ConstraintException; use SP\Domain\Core\Exceptions\QueryException; use SP\Domain\User\Ports\UserToUserGroupServiceInterface; @@ -62,8 +63,8 @@ final class AccountAclService extends Service implements AccountAclServiceInterf private UserLoginResponse $userData; public function __construct( - Application $application, - Acl $acl, + Application $application, + AclInterface $acl, UserToUserGroupServiceInterface $userGroupService, ?FileCacheInterface $fileCache = null ) { diff --git a/lib/SP/Domain/Account/Services/AccountService.php b/lib/SP/Domain/Account/Services/AccountService.php index e1effbc4..51d7c642 100644 --- a/lib/SP/Domain/Account/Services/AccountService.php +++ b/lib/SP/Domain/Account/Services/AccountService.php @@ -28,7 +28,6 @@ use SP\Core\Application; use SP\DataModel\ItemPreset\AccountPrivate; use SP\DataModel\ItemSearchData; use SP\DataModel\ProfileData; -use SP\Domain\Account\Adapters\AccountData; use SP\Domain\Account\Dtos\AccountCreateDto; use SP\Domain\Account\Dtos\AccountEnrichedDto; use SP\Domain\Account\Dtos\AccountHistoryCreateDto; @@ -37,7 +36,7 @@ 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\Models\AccountView; use SP\Domain\Account\Ports\AccountCryptServiceInterface; use SP\Domain\Account\Ports\AccountHistoryServiceInterface; use SP\Domain\Account\Ports\AccountItemsServiceInterface; @@ -71,17 +70,17 @@ use function SP\__u; final class AccountService extends Service implements AccountServiceInterface { public function __construct( - Application $application, - private AccountRepositoryInterface $accountRepository, + Application $application, + private AccountRepositoryInterface $accountRepository, private AccountToUserGroupRepositoryInterface $accountToUserGroupRepository, private AccountToUserRepositoryInterface $accountToUserRepository, - private AccountToTagRepositoryInterface $accountToTagRepository, - private ItemPresetServiceInterface $itemPresetService, - private AccountHistoryServiceInterface $accountHistoryService, - private AccountItemsServiceInterface $accountItemsService, - private AccountPresetServiceInterface $accountPresetService, - private ConfigServiceInterface $configService, - private AccountCryptServiceInterface $accountCryptService + private AccountToTagRepositoryInterface $accountToTagRepository, + private ItemPresetServiceInterface $itemPresetService, + private AccountHistoryServiceInterface $accountHistoryService, + private AccountItemsServiceInterface $accountItemsService, + private AccountPresetServiceInterface $accountPresetService, + private ConfigServiceInterface $configService, + private AccountCryptServiceInterface $accountCryptService ) { parent::__construct($application); } @@ -169,13 +168,13 @@ final class AccountService extends Service implements AccountServiceInterface } /** - * @param int $id + * @param int $id * - * @return AccountDataView + * @return AccountView * @throws SPException * @throws NoSuchItemException */ - public function getByIdEnriched(int $id): AccountDataView + public function getByIdEnriched(int $id): AccountView { $result = $this->accountRepository->getByIdEnriched($id); @@ -183,7 +182,7 @@ final class AccountService extends Service implements AccountServiceInterface throw new NoSuchItemException(__u('The account doesn\'t exist')); } - return $result->getData(AccountDataView::class); + return $result->getData(AccountView::class); } /** @@ -230,7 +229,7 @@ final class AccountService extends Service implements AccountServiceInterface } /** - * @param int $id + * @param int $id * * @return Account * @throws SPException @@ -257,7 +256,7 @@ final class AccountService extends Service implements AccountServiceInterface protected function userCanChangeOwner( UserLoginResponse $userData, ProfileData $userProfile, - Account $account + Account $account ): bool { return $userData->getIsAdminApp() || $userData->getIsAdminAcc() || ($userProfile->isAccPermission() && $userData->getId() === $account->getUserId()); @@ -273,7 +272,7 @@ final class AccountService extends Service implements AccountServiceInterface protected function userCanChangeGroup( UserLoginResponse $userData, ProfileData $userProfile, - Account $account + Account $account ): bool { return $this->userCanChangeOwner($userData, $userProfile, $account) || ($userProfile->isAccPermission() && $userData->getUserGroupId() === $account->getUserGroupId()); @@ -385,7 +384,7 @@ final class AccountService extends Service implements AccountServiceInterface /** * Updates external items for the account * - * @param int $id + * @param int $id * @param AccountUpdateDto $accountUpdateDto * * @throws ServiceException @@ -429,7 +428,7 @@ final class AccountService extends Service implements AccountServiceInterface } /** - * @param int $id + * @param int $id * @param AccountUpdateDto $accountUpdateDto * * @throws ServiceException @@ -454,7 +453,7 @@ final class AccountService extends Service implements AccountServiceInterface /** * Updates an already encrypted password data from a master password changing action * - * @param int $id + * @param int $id * @param EncryptedPassword $encryptedPassword * * @return void @@ -534,7 +533,7 @@ final class AccountService extends Service implements AccountServiceInterface } /** - * @param int[] $ids + * @param int[] $ids * * @throws SPException * @throws ServiceException @@ -547,7 +546,7 @@ final class AccountService extends Service implements AccountServiceInterface } /** - * @param int|null $id + * @param int|null $id * * @return array * @throws ConstraintException @@ -560,7 +559,7 @@ final class AccountService extends Service implements AccountServiceInterface } /** - * @param int $id + * @param int $id * * @return array * @throws ConstraintException @@ -590,7 +589,7 @@ final class AccountService extends Service implements AccountServiceInterface } /** - * @return AccountData[] + * @return Account[] * @throws SPException */ public function getAllBasic(): array diff --git a/lib/SP/Domain/Account/Services/PublicLinkService.php b/lib/SP/Domain/Account/Services/PublicLinkService.php index 03b2e4e3..4d3e2582 100644 --- a/lib/SP/Domain/Account/Services/PublicLinkService.php +++ b/lib/SP/Domain/Account/Services/PublicLinkService.php @@ -29,8 +29,8 @@ use Defuse\Crypto\Exception\EnvironmentIsBrokenException; use SP\Core\Application; use SP\Core\Crypt\Vault; use SP\DataModel\ItemSearchData; -use SP\DataModel\PublicLinkData; -use SP\DataModel\PublicLinkListData; +use SP\DataModel\PublicLinkList; +use SP\Domain\Account\Models\PublicLink; use SP\Domain\Account\Ports\AccountServiceInterface; use SP\Domain\Account\Ports\PublicLinkRepositoryInterface; use SP\Domain\Account\Ports\PublicLinkServiceInterface; @@ -66,11 +66,11 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf public const TYPE_ACCOUNT = 1; public function __construct( - Application $application, - private PublicLinkRepositoryInterface $publicLinkRepository, - private RequestInterface $request, - private AccountServiceInterface $accountService, - private CryptInterface $crypt + Application $application, + private readonly PublicLinkRepositoryInterface $publicLinkRepository, + private readonly RequestInterface $request, + private readonly AccountServiceInterface $accountService, + private readonly CryptInterface $crypt ) { parent::__construct($application); } @@ -80,7 +80,7 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf */ public static function getLinkForHash(string $baseUrl, string $hash): string { - return (new Uri($baseUrl))->addParam('r', 'account/viewLink/'.$hash)->getUri(); + return (new Uri($baseUrl))->addParam('r', 'account/viewLink/' . $hash)->getUri(); } /** @@ -119,17 +119,17 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf } return $this->publicLinkRepository - ->refresh($this->buildPublicLink(PublicLinkData::buildFromSimpleModel($result->getData()))); + ->refresh($this->buildPublicLink(PublicLink::buildFromSimpleModel($result->getData()))); } /** - * @param int $id + * @param int $id * - * @return PublicLinkListData + * @return PublicLinkList * @throws SPException * @throws NoSuchItemException */ - public function getById(int $id): PublicLinkListData + public function getById(int $id): PublicLinkList { $result = $this->publicLinkRepository->getById($id); @@ -137,13 +137,13 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf throw new NoSuchItemException(__u('Link not found')); } - return PublicLinkListData::buildFromSimpleModel($result->getData()); + return PublicLinkList::buildFromSimpleModel($result->getData()); } /** - * @param PublicLinkData $publicLinkData + * @param PublicLink $publicLink * - * @return PublicLinkData + * @return PublicLink * @throws EnvironmentIsBrokenException * @throws ConstraintException * @throws CryptException @@ -151,22 +151,19 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf * @throws ServiceException * @throws NoSuchItemException */ - private function buildPublicLink(PublicLinkData $publicLinkData): PublicLinkData + private function buildPublicLink(PublicLink $publicLink): PublicLink { $key = $this->getPublicLinkKey(); - $publicLinkDataClone = clone $publicLinkData; - - $publicLinkDataClone->setHash($key->getHash()); - $publicLinkDataClone->setData($this->getSecuredLinkData($publicLinkDataClone->getItemId(), $key)); - $publicLinkDataClone->setDateExpire(self::calcDateExpire($this->config)); - $publicLinkDataClone->setMaxCountViews($this->config->getConfigData()->getPublinksMaxViews()); - - if ($publicLinkDataClone->getUserId() === null) { - $publicLinkDataClone->setUserId($this->context->getUserData()->getId()); - } - - return $publicLinkDataClone; + return $publicLink->mutate( + [ + 'hash' => $key->getHash(), + 'data' => $this->getSecuredLinkData($publicLink->getItemId(), $key), + 'dateExpire' => self::calcDateExpire($this->config), + 'maxCountViews' => $this->config->getConfigData()->getPublinksMaxViews(), + 'userId' => $publicLink->getUserId() ?? $this->context->getUserData()->getId() + ] + ); } /** @@ -183,7 +180,7 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf /** * Obtener los datos de una cuenta y encriptarlos para el enlace * - * @param int $itemId + * @param int $itemId * @param PublicLinkKey $key * * @return string @@ -195,18 +192,20 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf */ private function getSecuredLinkData(int $itemId, PublicLinkKey $key): string { - $accountData = $this->accountService->getDataForLink($itemId); + $account = $this->accountService->getDataForLink($itemId); - $accountDataClone = $accountData->mutate([ + $properties = [ 'pass' => $this->crypt->decrypt( - $accountData['pass'], - $accountData['key'], + $account['pass'], + $account['key'], $this->getMasterKeyFromContext() ), - 'key' => null, - ]); + 'key' => null, + ]; - return Vault::factory($this->crypt)->saveData(serialize($accountDataClone), $key->getKey())->getSerialized(); + return Vault::factory($this->crypt) + ->saveData(serialize($account->mutate($properties)), $key->getKey()) + ->getSerialized(); } /** @@ -218,7 +217,7 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf } /** - * @param int $id + * @param int $id * * @return PublicLinkServiceInterface * @throws ConstraintException @@ -234,7 +233,7 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf /** * Deletes all the items for given ids * - * @param int[] $ids + * @param int[] $ids * * @throws ConstraintException * @throws QueryException @@ -257,7 +256,7 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf * @throws ConstraintException * @throws QueryException */ - public function create(PublicLinkData $itemData): int + public function create(PublicLink $itemData): int { return $this->publicLinkRepository->create($this->buildPublicLink($itemData))->getLastId(); } @@ -265,7 +264,7 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf /** * @throws SPException */ - public function getAllBasic(): array + public function getAll(): array { throw new ServiceException(__u('Not implemented')); } @@ -273,34 +272,31 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf /** * Incrementar el contador de visitas de un enlace * - * @param PublicLinkData $publicLinkData + * @param PublicLink $publicLink * * @throws ConstraintException * @throws QueryException * @throws ServiceException */ - public function addLinkView(PublicLinkData $publicLinkData): void + public function addLinkView(PublicLink $publicLink): void { $useInfo = array(); - if (empty($publicLinkData->getHash())) { + if (empty($publicLink->getHash())) { throw new ServiceException(__u('Public link hash not set')); } - if (!empty($publicLinkData->getUseInfo())) { - $publicLinkUseInfo = unserialize($publicLinkData->getUseInfo(), ['allowed_classes' => false]); + if (!empty($publicLink->getUseInfo())) { + $publicLinkUseInfo = unserialize($publicLink->getUseInfo(), ['allowed_classes' => false]); if (is_array($publicLinkUseInfo)) { $useInfo = $publicLinkUseInfo; } } - $useInfo[] = self::getUseInfo($publicLinkData->getHash(), $this->request); + $useInfo[] = self::getUseInfo($publicLink->getHash(), $this->request); - $publicLinkDataClone = clone $publicLinkData; - $publicLinkDataClone->setUseInfo($useInfo); - - $this->publicLinkRepository->addLinkView($publicLinkDataClone); + $this->publicLinkRepository->addLinkView($publicLink->mutate(['useInfo' => serialize($useInfo)])); } /** @@ -309,9 +305,9 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf public static function getUseInfo(string $hash, RequestInterface $request): array { return [ - 'who' => $request->getClientAddress(true), - 'time' => time(), - 'hash' => $hash, + 'who' => $request->getClientAddress(true), + 'time' => time(), + 'hash' => $hash, 'agent' => $request->getHeader('User-Agent'), 'https' => $request->isHttps(), ]; @@ -320,7 +316,7 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf /** * @throws SPException */ - public function getByHash(string $hash): PublicLinkData + public function getByHash(string $hash): PublicLink { $result = $this->publicLinkRepository->getByHash($hash); @@ -328,19 +324,19 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf throw new NoSuchItemException(__u('Link not found')); } - return PublicLinkData::buildFromSimpleModel($result->getData(Simple::class)); + return PublicLink::buildFromSimpleModel($result->getData(Simple::class)); } /** * Devolver el hash asociado a un elemento * - * @param int $itemId + * @param int $itemId * - * @return PublicLinkData + * @return PublicLink * @throws SPException * @throws NoSuchItemException */ - public function getHashForItem(int $itemId): PublicLinkData + public function getHashForItem(int $itemId): PublicLink { $result = $this->publicLinkRepository->getHashForItem($itemId); @@ -348,7 +344,7 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf throw new NoSuchItemException(__u('Link not found')); } - return PublicLinkData::buildFromSimpleModel($result->getData(Simple::class)); + return PublicLink::buildFromSimpleModel($result->getData(Simple::class)); } /** @@ -358,7 +354,7 @@ final class PublicLinkService extends Service implements PublicLinkServiceInterf * @throws ConstraintException * @throws QueryException */ - public function update(PublicLinkData $itemData): void + public function update(PublicLink $itemData): void { $this->publicLinkRepository->update($itemData); } diff --git a/lib/SP/Domain/Account/Services/UpgradePublicLinkService.php b/lib/SP/Domain/Account/Services/UpgradePublicLinkService.php index dae917ac..352ed176 100644 --- a/lib/SP/Domain/Account/Services/UpgradePublicLinkService.php +++ b/lib/SP/Domain/Account/Services/UpgradePublicLinkService.php @@ -29,11 +29,12 @@ use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\DataModel\PublickLinkOldData; -use SP\DataModel\PublicLinkData; +use SP\Domain\Account\Models\PublicLink; use SP\Domain\Account\Ports\PublicLinkRepositoryInterface; use SP\Domain\Account\Ports\UpgradePublicLinkServiceInterface; use SP\Domain\Common\Services\Service; use SP\Util\Util; + use function SP\__u; use function SP\processException; @@ -75,10 +76,10 @@ final class UpgradePublicLinkService extends Service implements UpgradePublicLin $data = Util::unserialize( PublickLinkOldData::class, $item['data'], - PublicLinkData::class + PublicLink::class ); - $itemData = new PublicLinkData([ + $itemData = new PublicLink([ 'id' => $item['id'], 'itemId' => $data->getItemId(), 'hash' => $data->getLinkHash(), diff --git a/lib/SP/Domain/Api/Services/ApiService.php b/lib/SP/Domain/Api/Services/ApiService.php index 941d41e5..0c1a0f2a 100644 --- a/lib/SP/Domain/Api/Services/ApiService.php +++ b/lib/SP/Domain/Api/Services/ApiService.php @@ -30,11 +30,11 @@ use SP\Core\Context\ContextException; use SP\Core\Crypt\Crypt; use SP\Core\Crypt\Hash; use SP\Core\Crypt\Vault; -use SP\DataModel\AuthToken; use SP\Domain\Api\Ports\ApiRequestInterface; use SP\Domain\Api\Ports\ApiServiceInterface; +use SP\Domain\Auth\Models\AuthToken as AuthTokenModel; use SP\Domain\Auth\Ports\AuthTokenServiceInterface; -use SP\Domain\Auth\Services\AuthTokenService; +use SP\Domain\Auth\Services\AuthToken; use SP\Domain\Common\Services\Service; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Core\Context\ContextInterface; @@ -65,26 +65,24 @@ final class ApiService extends Service implements ApiServiceInterface { private const STATUS_INITIALIZED = 0; private const STATUS_INITIALIZING = 1; - private TrackServiceInterface $trackService; - private TrackRequest $trackRequest; - private ?AuthToken $authTokenData = null; - private ?string $helpClass = null; - private ?int $status = null; + private TrackRequest $trackRequest; + private ?AuthTokenModel $authToken = null; + private ?string $helpClass = null; + private ?int $status = null; /** * @throws InvalidArgumentException */ public function __construct( - Application $application, - TrackServiceInterface $trackService, - private ApiRequestInterface $apiRequest, - private AuthTokenServiceInterface $authTokenService, - private UserServiceInterface $userService, - private UserProfileServiceInterface $userProfileService + Application $application, + private readonly TrackServiceInterface $trackService, + private readonly ApiRequestInterface $apiRequest, + private readonly AuthTokenServiceInterface $authTokenService, + private readonly UserServiceInterface $userService, + private readonly UserProfileServiceInterface $userProfileService ) { parent::__construct($application); - $this->trackService = $trackService; $this->trackRequest = $trackService->getTrackRequest(__CLASS__); } @@ -111,7 +109,7 @@ final class ApiService extends Service implements ApiServiceInterface } try { - $this->authTokenData = $this->authTokenService + $this->authToken = $this->authTokenService ->getTokenByToken($actionId, $this->getParam('authToken')); } catch (NoSuchItemException $e) { logger($e->getMessage(), 'ERROR'); @@ -125,13 +123,13 @@ final class ApiService extends Service implements ApiServiceInterface ); } - if ($this->authTokenData->getActionId() !== $actionId) { + if ($this->authToken->getActionId() !== $actionId) { $this->accessDenied(); } $this->setupUser(); - if (AuthTokenService::isSecuredAction($actionId)) { + if (AuthToken::isSecuredAction($actionId)) { $this->requireMasterPass(); } @@ -162,9 +160,9 @@ final class ApiService extends Service implements ApiServiceInterface /** * Devolver el valor de un parámetro * - * @param string $param - * @param bool $required Si es requerido - * @param mixed|null $default Valor por defecto + * @param string $param + * @param bool $required Si es requerido + * @param mixed|null $default Valor por defecto * * @return mixed * @throws ServiceException @@ -186,7 +184,7 @@ final class ApiService extends Service implements ApiServiceInterface /** * Devuelve la ayuda para una acción * - * @param string $action + * @param string $action * * @return array */ @@ -222,7 +220,7 @@ final class ApiService extends Service implements ApiServiceInterface private function setupUser(): void { $userLoginResponse = UserService::mapUserLoginResponse( - $this->userService->getById($this->authTokenData->getUserId()) + $this->userService->getById($this->authToken->getUserId()) ); $userLoginResponse->getIsDisabled() && $this->accessDenied(); @@ -253,12 +251,12 @@ final class ApiService extends Service implements ApiServiceInterface try { $tokenPass = $this->getParam('tokenPass', true); - Hash::checkHashKey($tokenPass, $this->authTokenData->getHash()) || $this->accessDenied(); + Hash::checkHashKey($tokenPass, $this->authToken->getHash()) || $this->accessDenied(); /** @var VaultInterface $vault */ - $vault = unserialize($this->authTokenData->getVault(), ['allowed_classes' => [Vault::class, Crypt::class]]); + $vault = unserialize($this->authToken->getVault(), ['allowed_classes' => [Vault::class, Crypt::class]]); - $key = sha1($tokenPass.$this->getParam('authToken')); + $key = sha1($tokenPass . $this->getParam('authToken')); if ($vault && ($pass = $vault->getData($key))) { return $pass; diff --git a/lib/SP/DataModel/AuthToken.php b/lib/SP/Domain/Auth/Models/AuthToken.php similarity index 94% rename from lib/SP/DataModel/AuthToken.php rename to lib/SP/Domain/Auth/Models/AuthToken.php index 38a59565..14a8344c 100644 --- a/lib/SP/DataModel/AuthToken.php +++ b/lib/SP/Domain/Auth/Models/AuthToken.php @@ -22,15 +22,18 @@ * along with sysPass. If not, see . */ -namespace SP\DataModel; +namespace SP\Domain\Auth\Models; use SP\Domain\Common\Models\Model; +use SP\Domain\Common\Models\SerializedModel; /** * Class AuthToken */ class AuthToken extends Model { + use SerializedModel; + protected ?int $id = null; protected ?int $userId = null; protected ?string $token = null; diff --git a/lib/SP/Domain/Auth/Ports/AuthTokenActionInterface.php b/lib/SP/Domain/Auth/Ports/AuthTokenActionInterface.php new file mode 100644 index 00000000..52a4b656 --- /dev/null +++ b/lib/SP/Domain/Auth/Ports/AuthTokenActionInterface.php @@ -0,0 +1,38 @@ +. + */ + +namespace SP\Domain\Auth\Ports; + +/** + * Interface AuthTokenAction + */ +interface AuthTokenActionInterface +{ + /** + * Devuelver un array de acciones posibles para los tokens + * + * @return array + */ + public function getTokenActions(): array; +} diff --git a/lib/SP/Domain/Auth/Ports/AuthTokenRepositoryInterface.php b/lib/SP/Domain/Auth/Ports/AuthTokenRepositoryInterface.php index 5f869881..63f4136b 100644 --- a/lib/SP/Domain/Auth/Ports/AuthTokenRepositoryInterface.php +++ b/lib/SP/Domain/Auth/Ports/AuthTokenRepositoryInterface.php @@ -25,8 +25,8 @@ namespace SP\Domain\Auth\Ports; use Exception; -use SP\DataModel\AuthToken; use SP\DataModel\ItemSearchData; +use SP\Domain\Auth\Models\AuthToken; use SP\Domain\Common\Ports\RepositoryInterface; use SP\Domain\Core\Exceptions\ConstraintException; use SP\Domain\Core\Exceptions\QueryException; diff --git a/lib/SP/Domain/Auth/Ports/AuthTokenServiceInterface.php b/lib/SP/Domain/Auth/Ports/AuthTokenServiceInterface.php index d9b00463..8536e534 100644 --- a/lib/SP/Domain/Auth/Ports/AuthTokenServiceInterface.php +++ b/lib/SP/Domain/Auth/Ports/AuthTokenServiceInterface.php @@ -24,13 +24,11 @@ namespace SP\Domain\Auth\Ports; - use Defuse\Crypto\Exception\CryptoException; use Defuse\Crypto\Exception\EnvironmentIsBrokenException; use Exception; -use SP\DataModel\AuthToken; use SP\DataModel\ItemSearchData; -use SP\Domain\Auth\Services\AuthTokenService; +use SP\Domain\Auth\Models\AuthToken as AuthTokenModel; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Core\Exceptions\ConstraintException; use SP\Domain\Core\Exceptions\QueryException; @@ -42,13 +40,14 @@ use SP\Infrastructure\Database\QueryResult; /** * Class AuthTokenService * - * @package SP\Domain\Common\Services\AuthToken + * @template T of AuthTokenModel */ interface AuthTokenServiceInterface { /** - * @throws ConstraintException + * @return QueryResult * @throws QueryException + * @throws ConstraintException */ public function search(ItemSearchData $itemSearchData): QueryResult; @@ -56,14 +55,14 @@ interface AuthTokenServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getById(int $id): AuthToken; + public function getById(int $id): AuthTokenModel; /** * @throws ConstraintException * @throws QueryException * @throws NoSuchItemException */ - public function delete(int $id): AuthTokenService; + public function delete(int $id): void; /** * Deletes all the items for given ids @@ -72,7 +71,7 @@ interface AuthTokenServiceInterface * @throws ConstraintException * @throws QueryException */ - public function deleteByIdBatch(array $ids): int; + public function deleteByIdBatch(array $ids): void; /** * @throws SPException @@ -81,12 +80,12 @@ interface AuthTokenServiceInterface * @throws ConstraintException * @throws QueryException */ - public function create(AuthToken $itemData): int; + public function create(AuthTokenModel $authToken): int; /** * @throws Exception */ - public function refreshAndUpdate(AuthToken $itemData): void; + public function refreshAndUpdate(AuthTokenModel $authToken): void; /** * @throws CryptoException @@ -97,14 +96,14 @@ interface AuthTokenServiceInterface * @throws NoSuchItemException * @throws ServiceException */ - public function update(AuthToken $itemData, ?string $token = null): void; + public function update(AuthTokenModel $authToken): void; /** * @throws SPException * @throws ConstraintException * @throws QueryException */ - public function updateRaw(AuthToken $itemData): void; + public function updateRaw(AuthTokenModel $authToken): void; /** * Devolver los datos de un token @@ -113,12 +112,12 @@ interface AuthTokenServiceInterface * @throws NoSuchItemException * @throws QueryException */ - public function getTokenByToken(int $actionId, string $token); + public function getTokenByToken(int $actionId, string $token): AuthTokenModel; /** - * @return AuthToken[] + * @return T[] * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array; + public function getAll(): array; } diff --git a/lib/SP/Domain/Auth/Services/AuthToken.php b/lib/SP/Domain/Auth/Services/AuthToken.php new file mode 100644 index 00000000..babbf45d --- /dev/null +++ b/lib/SP/Domain/Auth/Services/AuthToken.php @@ -0,0 +1,310 @@ +. + */ + +namespace SP\Domain\Auth\Services; + +use Defuse\Crypto\Exception\CryptoException; +use Defuse\Crypto\Exception\EnvironmentIsBrokenException; +use Exception; +use SP\Core\Application; +use SP\Core\Crypt\Hash; +use SP\Core\Crypt\Vault; +use SP\DataModel\ItemSearchData; +use SP\Domain\Auth\Models\AuthToken as AuthTokenModel; +use SP\Domain\Auth\Ports\AuthTokenRepositoryInterface; +use SP\Domain\Auth\Ports\AuthTokenServiceInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Common\Services\ServiceItemTrait; +use SP\Domain\Core\Acl\AclActionsInterface; +use SP\Domain\Core\Crypt\CryptInterface; +use SP\Domain\Core\Crypt\VaultInterface; +use SP\Domain\Core\Exceptions\ConstraintException; +use SP\Domain\Core\Exceptions\CryptException; +use SP\Domain\Core\Exceptions\QueryException; +use SP\Domain\Core\Exceptions\SPException; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Util\PasswordUtil; + +use function SP\__u; + +/** + * Class AuthTokenService + * + * @template T of AuthTokenModel + */ +final class AuthToken extends Service implements AuthTokenServiceInterface +{ + use ServiceItemTrait; + + private const SECURED_ACTIONS = [ + AclActionsInterface::ACCOUNT_VIEW_PASS, + AclActionsInterface::ACCOUNT_EDIT_PASS, + AclActionsInterface::ACCOUNT_CREATE, + ]; + + private const CAN_USE_SECURE_TOKEN_ACTIONS = [ + AclActionsInterface::ACCOUNT_VIEW, + AclActionsInterface::CATEGORY_VIEW, + AclActionsInterface::CLIENT_VIEW, + ]; + + /** + * @param Application $application + * @param AuthTokenRepositoryInterface $authTokenRepository + * @param CryptInterface $crypt + */ + public function __construct( + Application $application, + private readonly AuthTokenRepositoryInterface $authTokenRepository, + private readonly CryptInterface $crypt + ) { + parent::__construct($application); + } + + /** + * @param ItemSearchData $itemSearchData + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult + { + return $this->authTokenRepository->search($itemSearchData); + } + + /** + * @throws ConstraintException + * @throws QueryException + * @throws SPException + */ + public function getById(int $id): AuthTokenModel + { + return $this->authTokenRepository->getById($id)->getData(AuthTokenModel::class); + } + + /** + * @throws ConstraintException + * @throws QueryException + * @throws NoSuchItemException + */ + public function delete(int $id): void + { + if ($this->authTokenRepository->delete($id)->getAffectedNumRows() === 0) { + throw new NoSuchItemException(__u('Token not found')); + } + } + + /** + * Deletes all the items for given ids + * + * @throws ServiceException + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByIdBatch(array $ids): void + { + if ($this->authTokenRepository->deleteByIdBatch($ids)->getAffectedNumRows() === 0) { + throw new ServiceException(__u('Error while removing the tokens'), SPException::WARNING); + } + } + + /** + * @throws SPException + * @throws CryptoException + * @throws EnvironmentIsBrokenException + * @throws ConstraintException + * @throws QueryException + */ + public function create(AuthTokenModel $authToken): int + { + $secureAuthToken = $this->injectSecureData($authToken, $this->getOrBuildToken($authToken)); + + return $this->authTokenRepository->create($secureAuthToken)->getLastId(); + } + + /** + * Injects secure data for token + * + * @throws CryptException + * @throws ServiceException + */ + private function injectSecureData(AuthTokenModel $authToken, string $token): AuthTokenModel + { + if (self::isSecuredAction($authToken->getActionId()) + || self::canUseSecureTokenAction($authToken->getActionId()) + ) { + $properties = [ + 'vault' => $this->getSecureData($token, $authToken->getHash())->getSerialized(), + 'hash' => Hash::hashKey($authToken->getHash()) + ]; + } else { + $properties = [ + 'hash' => null + ]; + } + + $properties['token'] = $token; + $properties['createdBy'] = $this->context->getUserData()->getId(); + + return $authToken->mutate($properties); + } + + public static function isSecuredAction(int $action): bool + { + return in_array($action, self::SECURED_ACTIONS, true); + } + + public static function canUseSecureTokenAction(int $action): bool + { + return in_array($action, self::CAN_USE_SECURE_TOKEN_ACTIONS, true); + } + + /** + * Generar la llave segura del token + * + * @throws ServiceException + * @throws CryptException + */ + private function getSecureData(string $token, string $key): VaultInterface + { + return Vault::factory($this->crypt) + ->saveData( + $this->getMasterKeyFromContext(), + $key . $token + ); + } + + /** + * @param AuthTokenModel $authToken + * @return string|null + * @throws EnvironmentIsBrokenException + * @throws SPException + */ + private function getOrBuildToken(AuthTokenModel $authToken): ?string + { + $currentToken = $this->authTokenRepository->getTokenByUserId($authToken->getUserId()); + + return match ($currentToken->getNumRows()) { + 1 => $currentToken->getData(AuthTokenModel::class)->getToken(), + 0 => $this->generateToken() + }; + } + + /** + * Generar un token de acceso + * + * @throws EnvironmentIsBrokenException + */ + private function generateToken(): string + { + return PasswordUtil::generateRandomBytes(32); + } + + /** + * @throws Exception + */ + public function refreshAndUpdate(AuthTokenModel $authToken): void + { + $this->authTokenRepository->transactionAware( + function () use ($authToken) { + $token = $this->generateToken(); + $vault = serialize($this->getSecureData($token, $authToken->getHash())); + + $this->authTokenRepository->refreshTokenByUserId( + $authToken->getUserId(), + $token + ); + $this->authTokenRepository->refreshVaultByUserId( + $authToken->getUserId(), + $vault, + Hash::hashKey($authToken->getHash()) + ); + + $secureData = $this->injectSecureData($authToken, $token); + + $this->authTokenRepository->update($secureData); + }, + $this + ); + } + + /** + * @throws ConstraintException + * @throws CryptException + * @throws DuplicatedItemException + * @throws EnvironmentIsBrokenException + * @throws QueryException + * @throws SPException + * @throws ServiceException + */ + public function update(AuthTokenModel $authToken): void + { + $secureAuthToken = $this->injectSecureData($authToken, $this->getOrBuildToken($authToken)); + + $this->authTokenRepository->update($secureAuthToken); + } + + /** + * @throws SPException + * @throws ConstraintException + * @throws QueryException + */ + public function updateRaw(AuthTokenModel $authToken): void + { + $this->authTokenRepository->update($authToken); + } + + /** + * Devolver los datos de un token + * + * @throws ConstraintException + * @throws NoSuchItemException + * @throws QueryException + * @throws SPException + */ + public function getTokenByToken(int $actionId, string $token): AuthTokenModel + { + $result = $this->authTokenRepository->getTokenByToken($actionId, $token); + + if ($result->getNumRows() === 0) { + throw new NoSuchItemException(__u('Token not found')); + } + + return $result->getData(AuthTokenModel::class); + } + + /** + * @return AuthToken[] + * @throws ConstraintException + * @throws QueryException + * @throws SPException + */ + public function getAll(): array + { + return $this->authTokenRepository->getAll()->getDataAsArray(AuthTokenModel::class); + } +} diff --git a/lib/SP/Domain/Auth/Services/AuthTokenAction.php b/lib/SP/Domain/Auth/Services/AuthTokenAction.php new file mode 100644 index 00000000..ab6aeba6 --- /dev/null +++ b/lib/SP/Domain/Auth/Services/AuthTokenAction.php @@ -0,0 +1,80 @@ +. + */ + +namespace SP\Domain\Auth\Services; + +use SP\Core\Acl\Acl; +use SP\Domain\Auth\Ports\AuthTokenActionInterface; +use SP\Domain\Core\Acl\AclActionsInterface; +use SP\Domain\Core\Acl\AclInterface; + +/** + * Class AuthTokenAction + */ +final class AuthTokenAction implements AuthTokenActionInterface +{ + public function __construct(private readonly AclInterface $acl) + { + } + + /** + * Devuelver un array de acciones posibles para los tokens + * + * @return array + */ + public function getTokenActions(): array + { + return [ + AclActionsInterface::ACCOUNT_SEARCH => $this->acl->getInfoFor(AclActionsInterface::ACCOUNT_SEARCH), + AclActionsInterface::ACCOUNT_VIEW => $this->acl->getInfoFor(AclActionsInterface::ACCOUNT_VIEW), + AclActionsInterface::ACCOUNT_VIEW_PASS => $this->acl->getInfoFor(AclActionsInterface::ACCOUNT_VIEW_PASS), + AclActionsInterface::ACCOUNT_EDIT_PASS => $this->acl->getInfoFor(AclActionsInterface::ACCOUNT_EDIT_PASS), + AclActionsInterface::ACCOUNT_DELETE => $this->acl->getInfoFor(AclActionsInterface::ACCOUNT_DELETE), + AclActionsInterface::ACCOUNT_CREATE => $this->acl->getInfoFor(AclActionsInterface::ACCOUNT_CREATE), + AclActionsInterface::ACCOUNT_EDIT => $this->acl->getInfoFor(AclActionsInterface::ACCOUNT_EDIT), + AclActionsInterface::CATEGORY_SEARCH => $this->acl->getInfoFor(AclActionsInterface::CATEGORY_SEARCH), + AclActionsInterface::CATEGORY_VIEW => $this->acl->getInfoFor(AclActionsInterface::CATEGORY_VIEW), + AclActionsInterface::CATEGORY_CREATE => $this->acl->getInfoFor(AclActionsInterface::CATEGORY_CREATE), + AclActionsInterface::CATEGORY_EDIT => $this->acl->getInfoFor(AclActionsInterface::CATEGORY_EDIT), + AclActionsInterface::CATEGORY_DELETE => $this->acl->getInfoFor(AclActionsInterface::CATEGORY_DELETE), + AclActionsInterface::CLIENT_SEARCH => $this->acl->getInfoFor(AclActionsInterface::CLIENT_SEARCH), + AclActionsInterface::CLIENT_VIEW => $this->acl->getInfoFor(AclActionsInterface::CLIENT_VIEW), + AclActionsInterface::CLIENT_CREATE => $this->acl->getInfoFor(AclActionsInterface::CLIENT_CREATE), + AclActionsInterface::CLIENT_EDIT => $this->acl->getInfoFor(AclActionsInterface::CLIENT_EDIT), + AclActionsInterface::CLIENT_DELETE => $this->acl->getInfoFor(AclActionsInterface::CLIENT_DELETE), + AclActionsInterface::TAG_SEARCH => $this->acl->getInfoFor(AclActionsInterface::TAG_SEARCH), + AclActionsInterface::TAG_VIEW => $this->acl->getInfoFor(AclActionsInterface::TAG_VIEW), + AclActionsInterface::TAG_CREATE => $this->acl->getInfoFor(AclActionsInterface::TAG_CREATE), + AclActionsInterface::TAG_EDIT => $this->acl->getInfoFor(AclActionsInterface::TAG_EDIT), + AclActionsInterface::TAG_DELETE => $this->acl->getInfoFor(AclActionsInterface::TAG_DELETE), + AclActionsInterface::GROUP_VIEW => $this->acl->getInfoFor(AclActionsInterface::GROUP_VIEW), + AclActionsInterface::GROUP_CREATE => $this->acl->getInfoFor(AclActionsInterface::GROUP_CREATE), + AclActionsInterface::GROUP_EDIT => $this->acl->getInfoFor(AclActionsInterface::GROUP_EDIT), + AclActionsInterface::GROUP_DELETE => $this->acl->getInfoFor(AclActionsInterface::GROUP_DELETE), + AclActionsInterface::GROUP_SEARCH => $this->acl->getInfoFor(AclActionsInterface::GROUP_SEARCH), + AclActionsInterface::CONFIG_BACKUP_RUN => $this->acl->getInfoFor(AclActionsInterface::CONFIG_BACKUP_RUN), + AclActionsInterface::CONFIG_EXPORT_RUN => $this->acl->getInfoFor(AclActionsInterface::CONFIG_EXPORT_RUN), + ]; + } +} diff --git a/lib/SP/Domain/Auth/Services/AuthTokenService.php b/lib/SP/Domain/Auth/Services/AuthTokenService.php deleted file mode 100644 index 6aa4fe8e..00000000 --- a/lib/SP/Domain/Auth/Services/AuthTokenService.php +++ /dev/null @@ -1,337 +0,0 @@ -. - */ - -namespace SP\Domain\Auth\Services; - -use Defuse\Crypto\Exception\CryptoException; -use Defuse\Crypto\Exception\EnvironmentIsBrokenException; -use Exception; -use SP\Core\Acl\Acl; -use SP\Core\Application; -use SP\Core\Crypt\Hash; -use SP\Core\Crypt\Vault; -use SP\DataModel\AuthToken; -use SP\DataModel\ItemSearchData; -use SP\Domain\Auth\Ports\AuthTokenRepositoryInterface; -use SP\Domain\Auth\Ports\AuthTokenServiceInterface; -use SP\Domain\Common\Services\Service; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Common\Services\ServiceItemTrait; -use SP\Domain\Core\Acl\AclActionsInterface; -use SP\Domain\Core\Crypt\VaultInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Infrastructure\Auth\Repositories\AuthTokenRepository; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SP\Infrastructure\Database\QueryResult; -use SP\Util\PasswordUtil; - -/** - * Class AuthTokenService - * - * @package SP\Domain\Common\Services\AuthToken - */ -final class AuthTokenService extends Service implements AuthTokenServiceInterface -{ - use ServiceItemTrait; - - private const SECURED_ACTIONS = [ - AclActionsInterface::ACCOUNT_VIEW_PASS, - AclActionsInterface::ACCOUNT_EDIT_PASS, - AclActionsInterface::ACCOUNT_CREATE, - ]; - - private const CAN_USE_SECURE_TOKEN_ACTIONS = [ - AclActionsInterface::ACCOUNT_VIEW, - AclActionsInterface::CATEGORY_VIEW, - AclActionsInterface::CLIENT_VIEW, - ]; - - private AuthTokenRepository $authTokenRepository; - - public function __construct(Application $application, AuthTokenRepositoryInterface $authTokenRepository) - { - parent::__construct($application); - - $this->authTokenRepository = $authTokenRepository; - } - - - /** - * Devuelver un array de acciones posibles para los tokens - * - * @return array - */ - public static function getTokenActions(): array - { - return [ - AclActionsInterface::ACCOUNT_SEARCH => Acl::getActionInfo(AclActionsInterface::ACCOUNT_SEARCH), - AclActionsInterface::ACCOUNT_VIEW => Acl::getActionInfo(AclActionsInterface::ACCOUNT_VIEW), - AclActionsInterface::ACCOUNT_VIEW_PASS => Acl::getActionInfo(AclActionsInterface::ACCOUNT_VIEW_PASS), - AclActionsInterface::ACCOUNT_EDIT_PASS => Acl::getActionInfo(AclActionsInterface::ACCOUNT_EDIT_PASS), - AclActionsInterface::ACCOUNT_DELETE => Acl::getActionInfo(AclActionsInterface::ACCOUNT_DELETE), - AclActionsInterface::ACCOUNT_CREATE => Acl::getActionInfo(AclActionsInterface::ACCOUNT_CREATE), - AclActionsInterface::ACCOUNT_EDIT => Acl::getActionInfo(AclActionsInterface::ACCOUNT_EDIT), - AclActionsInterface::CATEGORY_SEARCH => Acl::getActionInfo(AclActionsInterface::CATEGORY_SEARCH), - AclActionsInterface::CATEGORY_VIEW => Acl::getActionInfo(AclActionsInterface::CATEGORY_VIEW), - AclActionsInterface::CATEGORY_CREATE => Acl::getActionInfo(AclActionsInterface::CATEGORY_CREATE), - AclActionsInterface::CATEGORY_EDIT => Acl::getActionInfo(AclActionsInterface::CATEGORY_EDIT), - AclActionsInterface::CATEGORY_DELETE => Acl::getActionInfo(AclActionsInterface::CATEGORY_DELETE), - AclActionsInterface::CLIENT_SEARCH => Acl::getActionInfo(AclActionsInterface::CLIENT_SEARCH), - AclActionsInterface::CLIENT_VIEW => Acl::getActionInfo(AclActionsInterface::CLIENT_VIEW), - AclActionsInterface::CLIENT_CREATE => Acl::getActionInfo(AclActionsInterface::CLIENT_CREATE), - AclActionsInterface::CLIENT_EDIT => Acl::getActionInfo(AclActionsInterface::CLIENT_EDIT), - AclActionsInterface::CLIENT_DELETE => Acl::getActionInfo(AclActionsInterface::CLIENT_DELETE), - AclActionsInterface::TAG_SEARCH => Acl::getActionInfo(AclActionsInterface::TAG_SEARCH), - AclActionsInterface::TAG_VIEW => Acl::getActionInfo(AclActionsInterface::TAG_VIEW), - AclActionsInterface::TAG_CREATE => Acl::getActionInfo(AclActionsInterface::TAG_CREATE), - AclActionsInterface::TAG_EDIT => Acl::getActionInfo(AclActionsInterface::TAG_EDIT), - AclActionsInterface::TAG_DELETE => Acl::getActionInfo(AclActionsInterface::TAG_DELETE), - AclActionsInterface::GROUP_VIEW => Acl::getActionInfo(AclActionsInterface::GROUP_VIEW), - AclActionsInterface::GROUP_CREATE => Acl::getActionInfo(AclActionsInterface::GROUP_CREATE), - AclActionsInterface::GROUP_EDIT => Acl::getActionInfo(AclActionsInterface::GROUP_EDIT), - AclActionsInterface::GROUP_DELETE => Acl::getActionInfo(AclActionsInterface::GROUP_DELETE), - AclActionsInterface::GROUP_SEARCH => Acl::getActionInfo(AclActionsInterface::GROUP_SEARCH), - AclActionsInterface::CONFIG_BACKUP_RUN => Acl::getActionInfo(AclActionsInterface::CONFIG_BACKUP_RUN), - AclActionsInterface::CONFIG_EXPORT_RUN => Acl::getActionInfo(AclActionsInterface::CONFIG_EXPORT_RUN), - ]; - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function search(ItemSearchData $itemSearchData): QueryResult - { - return $this->authTokenRepository->search($itemSearchData); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function getById(int $id): AuthToken - { - return $this->authTokenRepository->getById($id)->getData(); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function delete(int $id): AuthTokenService - { - if ($this->authTokenRepository->delete($id) === 0) { - throw new NoSuchItemException(__u('Token not found')); - } - - return $this; - } - - /** - * Deletes all the items for given ids - * - * @throws ServiceException - * @throws ConstraintException - * @throws QueryException - */ - public function deleteByIdBatch(array $ids): int - { - $count = $this->authTokenRepository->deleteByIdBatch($ids); - - if ($count !== count($ids)) { - throw new ServiceException( - __u('Error while removing the tokens'), - SPException::WARNING - ); - } - - return $count; - } - - /** - * @throws SPException - * @throws CryptoException - * @throws EnvironmentIsBrokenException - * @throws ConstraintException - * @throws QueryException - */ - public function create(AuthToken $itemData): int - { - return $this->authTokenRepository->create($this->injectSecureData($itemData)); - } - - /** - * Injects secure data for token - * - * @throws ServiceException - * @throws CryptoException - * @throws EnvironmentIsBrokenException - * @throws ConstraintException - * @throws QueryException - */ - private function injectSecureData(AuthToken $authTokenData, ?string $token = null): AuthToken - { - if ($token === null) { - $token = $this->authTokenRepository - ->getTokenByUserId($authTokenData->getUserId()) ?: $this->generateToken(); - } - - if (self::isSecuredAction($authTokenData->getActionId()) - || self::canUseSecureTokenAction($authTokenData->getActionId()) - ) { - $authTokenData->setVault( - $this->getSecureData($token, $authTokenData->getHash()) - ); - $authTokenData->setHash(Hash::hashKey($authTokenData->getHash())); - } else { - $authTokenData->setHash(null); - } - - $authTokenData->setToken($token); - $authTokenData->setCreatedBy($this->context->getUserData()->getId()); - - return $authTokenData; - } - - /** - * Generar un token de acceso - * - * @throws EnvironmentIsBrokenException - */ - private function generateToken(): string - { - return PasswordUtil::generateRandomBytes(32); - } - - public static function isSecuredAction(int $action): bool - { - return in_array($action, self::SECURED_ACTIONS, true); - } - - public static function canUseSecureTokenAction(int $action): bool - { - return in_array($action, self::CAN_USE_SECURE_TOKEN_ACTIONS, true); - } - - /** - * Generar la llave segura del token - * - * @throws ServiceException - * @throws CryptoException - */ - private function getSecureData(string $token, string $key): VaultInterface - { - return (new Vault())->saveData( - $this->getMasterKeyFromContext(), - $key.$token - ); - } - - /** - * @throws Exception - */ - public function refreshAndUpdate(AuthToken $itemData): void - { - $this->transactionAware( - function () use ($itemData) { - $token = $this->generateToken(); - $vault = serialize( - $this->getSecureData($token, $itemData->getHash()) - ); - - $this->authTokenRepository->refreshTokenByUserId( - $itemData->getUserId(), - $token - ); - $this->authTokenRepository->refreshVaultByUserId( - $itemData->getUserId(), - $vault, - Hash::hashKey($itemData->getHash()) - ); - - $this->update($itemData, $token); - } - ); - } - - /** - * @throws CryptoException - * @throws EnvironmentIsBrokenException - * @throws ConstraintException - * @throws QueryException - * @throws DuplicatedItemException - * @throws NoSuchItemException - * @throws ServiceException - */ - public function update(AuthToken $itemData, ?string $token = null): void - { - if ($this->authTokenRepository->update($this->injectSecureData($itemData, $token)) === 0) { - throw new NoSuchItemException(__u('Token not found')); - } - } - - /** - * @throws SPException - * @throws ConstraintException - * @throws QueryException - */ - public function updateRaw(AuthToken $itemData): void - { - if ($this->authTokenRepository->update($itemData) === 0) { - throw new NoSuchItemException(__u('Token not found')); - } - } - - /** - * Devolver los datos de un token - * - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function getTokenByToken(int $actionId, string $token) - { - $result = $this->authTokenRepository->getTokenByToken($actionId, $token); - - if ($result->getNumRows() === 0) { - throw new NoSuchItemException(__u('Token not found')); - } - - return $result->getData(); - } - - /** - * @return AuthToken[] - * @throws ConstraintException - * @throws QueryException - */ - public function getAllBasic(): array - { - return $this->authTokenRepository->getAll()->getDataAsArray(); - } -} diff --git a/lib/SP/Domain/Auth/Services/UpgradeAuthTokenService.php b/lib/SP/Domain/Auth/Services/UpgradeAuthTokenService.php index 7fa6aa5f..31e28ad5 100644 --- a/lib/SP/Domain/Auth/Services/UpgradeAuthTokenService.php +++ b/lib/SP/Domain/Auth/Services/UpgradeAuthTokenService.php @@ -78,7 +78,7 @@ final class UpgradeAuthTokenService extends Service try { $this->transactionAware( function () { - foreach ($this->authTokenService->getAllBasic() as $item) { + foreach ($this->authTokenService->getAll() as $item) { $itemData = clone $item; $itemData->setActionId($this->actionMapper($item->getActionId())); diff --git a/lib/SP/Domain/Category/Ports/CategoryServiceInterface.php b/lib/SP/Domain/Category/Ports/CategoryServiceInterface.php index 02bd1b00..4eaf5bb5 100644 --- a/lib/SP/Domain/Category/Ports/CategoryServiceInterface.php +++ b/lib/SP/Domain/Category/Ports/CategoryServiceInterface.php @@ -100,5 +100,5 @@ interface CategoryServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array; + public function getAll(): array; } diff --git a/lib/SP/Domain/Category/Services/CategoryService.php b/lib/SP/Domain/Category/Services/CategoryService.php index 3b3d57f2..53e8401e 100644 --- a/lib/SP/Domain/Category/Services/CategoryService.php +++ b/lib/SP/Domain/Category/Services/CategoryService.php @@ -158,7 +158,7 @@ final class CategoryService extends Service implements CategoryServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array + public function getAll(): array { return $this->categoryRepository->getAll()->getDataAsArray(); } diff --git a/lib/SP/Domain/Client/Ports/ClientServiceInterface.php b/lib/SP/Domain/Client/Ports/ClientServiceInterface.php index 028f7451..f03c4a2c 100644 --- a/lib/SP/Domain/Client/Ports/ClientServiceInterface.php +++ b/lib/SP/Domain/Client/Ports/ClientServiceInterface.php @@ -104,7 +104,7 @@ interface ClientServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array; + public function getAll(): array; /** * Returns all clients visible for a given user diff --git a/lib/SP/Domain/Client/Services/ClientService.php b/lib/SP/Domain/Client/Services/ClientService.php index 3db5d11b..229dbb01 100644 --- a/lib/SP/Domain/Client/Services/ClientService.php +++ b/lib/SP/Domain/Client/Services/ClientService.php @@ -169,7 +169,7 @@ final class ClientService extends Service implements ClientServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array + public function getAll(): array { return $this->clientRepository->getAll()->getDataAsArray(); } diff --git a/lib/SP/Domain/Common/Models/Model.php b/lib/SP/Domain/Common/Models/Model.php index 05234b3e..284c2796 100644 --- a/lib/SP/Domain/Common/Models/Model.php +++ b/lib/SP/Domain/Common/Models/Model.php @@ -123,7 +123,7 @@ abstract class Model implements JsonSerializable, ArrayAccess * * @param array $properties * - * @return $this + * @return static */ final public function mutate(array $properties): static { diff --git a/lib/SP/Domain/Common/Models/SerializedModel.php b/lib/SP/Domain/Common/Models/SerializedModel.php index ce48ead1..6ade0c9d 100644 --- a/lib/SP/Domain/Common/Models/SerializedModel.php +++ b/lib/SP/Domain/Common/Models/SerializedModel.php @@ -33,11 +33,11 @@ use SP\Util\Util; trait SerializedModel { /** - * @template T - * @param class-string|null $class + * @template THydrate + * @param class-string|null $class * @param string $property * - * @return T|null + * @return THydrate|null * @throws NoSuchPropertyException */ public function hydrate(?string $class = null, string $property = 'data'): mixed diff --git a/lib/SP/Domain/Common/Services/Service.php b/lib/SP/Domain/Common/Services/Service.php index 505fc23e..5efc93fb 100644 --- a/lib/SP/Domain/Common/Services/Service.php +++ b/lib/SP/Domain/Common/Services/Service.php @@ -33,6 +33,8 @@ use SP\Domain\Config\Ports\ConfigInterface; use SP\Domain\Core\Context\ContextInterface; use SP\Domain\Core\Events\EventDispatcherInterface; +use SP\Domain\Core\Exceptions\CryptException; + use function SP\__u; use function SP\logger; @@ -58,6 +60,7 @@ abstract class Service /** * @throws ServiceException + * @throws CryptException */ final protected function getMasterKeyFromContext(): string { @@ -82,6 +85,7 @@ abstract class Service /** * @throws ServiceException + * @throws CryptException */ final protected function setMasterKeyInContext(string $masterPass): void { diff --git a/lib/SP/Domain/Common/Services/ServiceItemTrait.php b/lib/SP/Domain/Common/Services/ServiceItemTrait.php index 7c5d1212..b9507d8b 100644 --- a/lib/SP/Domain/Common/Services/ServiceItemTrait.php +++ b/lib/SP/Domain/Common/Services/ServiceItemTrait.php @@ -36,5 +36,5 @@ trait ServiceItemTrait * * @return mixed */ - abstract public function getAllBasic(); -} \ No newline at end of file + abstract public function getAll(); +} diff --git a/lib/SP/Domain/Core/Acl/AclInterface.php b/lib/SP/Domain/Core/Acl/AclInterface.php new file mode 100644 index 00000000..a7a332e8 --- /dev/null +++ b/lib/SP/Domain/Core/Acl/AclInterface.php @@ -0,0 +1,52 @@ +. + */ + +namespace SP\Domain\Core\Acl; + +/** + * Interface AclInterface + */ +interface AclInterface +{ + /** + * Obtener el nombre de la acción indicada + * + * @param int $actionId El id de la acción + * @param bool $translate + * + * @return string + * @internal param bool $translate Si se devuelve el nombre corto de la acción + */ + public function getInfoFor(int $actionId, bool $translate = true): string; + + /** + * Returns action route + */ + public function getRouteFor(string $actionId): string; + + /** + * Comprobar los permisos de acceso del usuario a los módulos de la aplicación. + */ + public function checkUserAccess(int $action, int $userId = 0): bool; +} diff --git a/lib/SP/Domain/CustomField/Ports/CustomFieldDefServiceInterface.php b/lib/SP/Domain/CustomField/Ports/CustomFieldDefServiceInterface.php index e1541be8..c120baeb 100644 --- a/lib/SP/Domain/CustomField/Ports/CustomFieldDefServiceInterface.php +++ b/lib/SP/Domain/CustomField/Ports/CustomFieldDefServiceInterface.php @@ -95,5 +95,5 @@ interface CustomFieldDefServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array; + public function getAll(): array; } diff --git a/lib/SP/Domain/CustomField/Ports/CustomFieldTypeServiceInterface.php b/lib/SP/Domain/CustomField/Ports/CustomFieldTypeServiceInterface.php index 4df6ad07..7232a985 100644 --- a/lib/SP/Domain/CustomField/Ports/CustomFieldTypeServiceInterface.php +++ b/lib/SP/Domain/CustomField/Ports/CustomFieldTypeServiceInterface.php @@ -43,7 +43,7 @@ interface CustomFieldTypeServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array; + public function getAll(): array; /** * Returns all the items diff --git a/lib/SP/Domain/CustomField/Services/CustomFieldDefService.php b/lib/SP/Domain/CustomField/Services/CustomFieldDefService.php index dbb94956..e5f997c4 100644 --- a/lib/SP/Domain/CustomField/Services/CustomFieldDefService.php +++ b/lib/SP/Domain/CustomField/Services/CustomFieldDefService.php @@ -209,7 +209,7 @@ final class CustomFieldDefService extends Service implements CustomFieldDefServi * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array + public function getAll(): array { return $this->customFieldDefRepository->getAll()->getDataAsArray(); } diff --git a/lib/SP/Domain/CustomField/Services/CustomFieldTypeService.php b/lib/SP/Domain/CustomField/Services/CustomFieldTypeService.php index a2c22595..89c99e1d 100644 --- a/lib/SP/Domain/CustomField/Services/CustomFieldTypeService.php +++ b/lib/SP/Domain/CustomField/Services/CustomFieldTypeService.php @@ -60,7 +60,7 @@ final class CustomFieldTypeService extends Service implements CustomFieldTypeSer * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array + public function getAll(): array { return $this->getAll(); } diff --git a/lib/SP/Domain/CustomField/Services/UpgradeCustomFieldDefinitionService.php b/lib/SP/Domain/CustomField/Services/UpgradeCustomFieldDefinitionService.php index eba9bbd4..6e858589 100644 --- a/lib/SP/Domain/CustomField/Services/UpgradeCustomFieldDefinitionService.php +++ b/lib/SP/Domain/CustomField/Services/UpgradeCustomFieldDefinitionService.php @@ -212,7 +212,7 @@ final class UpgradeCustomFieldDefinitionService extends Service try { $this->transactionAware( function () { - foreach ($this->customFieldDefService->getAllBasic() as $item) { + foreach ($this->customFieldDefService->getAll() as $item) { $itemData = clone $item; $itemData->setModuleId($this->moduleMapper((int)$item->getModuleId())); diff --git a/lib/SP/Domain/Export/Services/XmlExportService.php b/lib/SP/Domain/Export/Services/XmlExportService.php index 990898a4..702b2c7b 100644 --- a/lib/SP/Domain/Export/Services/XmlExportService.php +++ b/lib/SP/Domain/Export/Services/XmlExportService.php @@ -263,7 +263,7 @@ final class XmlExportService extends Service implements XmlExportServiceInterfac new Event($this, EventMessage::factory()->addDescription(__u('Exporting categories'))) ); - $categories = $this->categoryService->getAllBasic(); + $categories = $this->categoryService->getAll(); // Crear el nodo de categorías $nodeCategories = $this->xml->createElement('Categories'); @@ -378,7 +378,7 @@ final class XmlExportService extends Service implements XmlExportServiceInterfac new Event($this, EventMessage::factory()->addDescription(__u('Exporting clients'))) ); - $clients = $this->clientService->getAllBasic(); + $clients = $this->clientService->getAll(); // Crear el nodo de clientes $nodeClients = $this->xml->createElement('Clients'); @@ -423,7 +423,7 @@ final class XmlExportService extends Service implements XmlExportServiceInterfac new Event($this, EventMessage::factory()->addDescription(__u('Exporting tags'))) ); - $tags = $this->tagService->getAllBasic(); + $tags = $this->tagService->getAll(); // Crear el nodo de etiquetas $nodeTags = $this->xml->createElement('Tags'); diff --git a/lib/SP/Domain/Tag/Ports/TagServiceInterface.php b/lib/SP/Domain/Tag/Ports/TagServiceInterface.php index 2b3d2ca5..44d94922 100644 --- a/lib/SP/Domain/Tag/Ports/TagServiceInterface.php +++ b/lib/SP/Domain/Tag/Ports/TagServiceInterface.php @@ -95,5 +95,5 @@ interface TagServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array; + public function getAll(): array; } diff --git a/lib/SP/Domain/Tag/Services/TagService.php b/lib/SP/Domain/Tag/Services/TagService.php index 87e84873..a4592534 100644 --- a/lib/SP/Domain/Tag/Services/TagService.php +++ b/lib/SP/Domain/Tag/Services/TagService.php @@ -154,7 +154,7 @@ final class TagService extends Service implements TagServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array + public function getAll(): array { return $this->tagRepository->getAll(); } diff --git a/lib/SP/Domain/User/Ports/UserGroupServiceInterface.php b/lib/SP/Domain/User/Ports/UserGroupServiceInterface.php index 305bf86a..5abf6b56 100644 --- a/lib/SP/Domain/User/Ports/UserGroupServiceInterface.php +++ b/lib/SP/Domain/User/Ports/UserGroupServiceInterface.php @@ -85,7 +85,7 @@ interface UserGroupServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array; + public function getAll(): array; /** * Returns the item for given name diff --git a/lib/SP/Domain/User/Ports/UserProfileServiceInterface.php b/lib/SP/Domain/User/Ports/UserProfileServiceInterface.php index 7b37f1d2..c6f48ce2 100644 --- a/lib/SP/Domain/User/Ports/UserProfileServiceInterface.php +++ b/lib/SP/Domain/User/Ports/UserProfileServiceInterface.php @@ -97,5 +97,5 @@ interface UserProfileServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array; + public function getAll(): array; } diff --git a/lib/SP/Domain/User/Ports/UserServiceInterface.php b/lib/SP/Domain/User/Ports/UserServiceInterface.php index 79c09183..17804820 100644 --- a/lib/SP/Domain/User/Ports/UserServiceInterface.php +++ b/lib/SP/Domain/User/Ports/UserServiceInterface.php @@ -162,7 +162,7 @@ interface UserServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array; + public function getAll(): array; /** * Obtener el email de los usuarios de un grupo diff --git a/lib/SP/Domain/User/Services/UserGroupService.php b/lib/SP/Domain/User/Services/UserGroupService.php index d8a8c758..c281b16f 100644 --- a/lib/SP/Domain/User/Services/UserGroupService.php +++ b/lib/SP/Domain/User/Services/UserGroupService.php @@ -180,7 +180,7 @@ final class UserGroupService extends Service implements UserGroupServiceInterfac * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array + public function getAll(): array { return $this->userGroupRepository->getAll()->getDataAsArray(); } diff --git a/lib/SP/Domain/User/Services/UserProfileService.php b/lib/SP/Domain/User/Services/UserProfileService.php index ef64ee0d..27edb116 100644 --- a/lib/SP/Domain/User/Services/UserProfileService.php +++ b/lib/SP/Domain/User/Services/UserProfileService.php @@ -167,7 +167,7 @@ final class UserProfileService extends Service implements UserProfileServiceInte * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array + public function getAll(): array { return $this->userProfileRepository->getAll()->getDataAsArray(); } diff --git a/lib/SP/Domain/User/Services/UserService.php b/lib/SP/Domain/User/Services/UserService.php index e2a21a95..36635561 100644 --- a/lib/SP/Domain/User/Services/UserService.php +++ b/lib/SP/Domain/User/Services/UserService.php @@ -352,7 +352,7 @@ final class UserService extends Service implements UserServiceInterface * @throws ConstraintException * @throws QueryException */ - public function getAllBasic(): array + public function getAll(): array { return $this->userRepository->getBasicInfo()->getDataAsArray(); } diff --git a/lib/SP/Infrastructure/Account/Repositories/AccountRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountRepository.php index 320c2ed3..5617cea0 100644 --- a/lib/SP/Infrastructure/Account/Repositories/AccountRepository.php +++ b/lib/SP/Infrastructure/Account/Repositories/AccountRepository.php @@ -28,7 +28,7 @@ use Aura\SqlQuery\QueryFactory; use SP\DataModel\ItemSearchData; use SP\Domain\Account\Dtos\EncryptedPassword; use SP\Domain\Account\Models\Account; -use SP\Domain\Account\Models\AccountDataView; +use SP\Domain\Account\Models\AccountView; use SP\Domain\Account\Models\AccountSearchView; use SP\Domain\Account\Ports\AccountFilterUserInterface; use SP\Domain\Account\Ports\AccountRepositoryInterface; @@ -409,12 +409,12 @@ final class AccountRepository extends Repository implements AccountRepositoryInt $query = $this->queryFactory ->newSelect() ->from('account_data_v') - ->cols(AccountDataView::getCols()) + ->cols(AccountView::getCols()) ->where('id = :id') ->bindValues(['id' => $accountId]) ->limit(1); - $queryData = QueryData::buildWithMapper($query, AccountDataView::class) + $queryData = QueryData::buildWithMapper($query, AccountView::class) ->setOnErrorMessage(__u('Error while retrieving account\'s data')); return $this->db->doSelect($queryData); diff --git a/lib/SP/Infrastructure/Account/Repositories/PublicLinkRepository.php b/lib/SP/Infrastructure/Account/Repositories/PublicLinkRepository.php index 4311caf1..488974bc 100644 --- a/lib/SP/Infrastructure/Account/Repositories/PublicLinkRepository.php +++ b/lib/SP/Infrastructure/Account/Repositories/PublicLinkRepository.php @@ -25,7 +25,7 @@ namespace SP\Infrastructure\Account\Repositories; use SP\DataModel\ItemSearchData; -use SP\DataModel\PublicLinkData; +use SP\Domain\Account\Models\PublicLink; use SP\Domain\Account\Ports\PublicLinkRepositoryInterface; use SP\Domain\Core\Exceptions\ConstraintException; use SP\Domain\Core\Exceptions\QueryException; @@ -185,14 +185,14 @@ final class PublicLinkRepository extends Repository implements PublicLinkReposit /** * Creates an item * - * @param PublicLinkData $publicLinkData + * @param PublicLink $publicLinkData * * @return QueryResult * @throws DuplicatedItemException * @throws QueryException * @throws ConstraintException */ - public function create(PublicLinkData $publicLinkData): QueryResult + public function create(PublicLink $publicLinkData): QueryResult { if ($this->checkDuplicatedOnAdd($publicLinkData->getItemId())) { throw new DuplicatedItemException(__u('Link already created')); @@ -242,13 +242,13 @@ final class PublicLinkRepository extends Repository implements PublicLinkReposit /** * Incrementar el contador de visitas de un enlace * - * @param PublicLinkData $publicLinkData + * @param \SP\Domain\Account\Models\PublicLink $publicLinkData * * @return bool * @throws ConstraintException * @throws QueryException */ - public function addLinkView(PublicLinkData $publicLinkData): bool + public function addLinkView(PublicLink $publicLinkData): bool { $query = $this->queryFactory ->newUpdate() @@ -267,13 +267,13 @@ final class PublicLinkRepository extends Repository implements PublicLinkReposit /** * Updates an item * - * @param PublicLinkData $publicLinkData + * @param PublicLink $publicLinkData * * @return bool * @throws ConstraintException * @throws QueryException */ - public function update(PublicLinkData $publicLinkData): bool + public function update(PublicLink $publicLinkData): bool { $query = $this->queryFactory ->newUpdate() @@ -300,14 +300,14 @@ final class PublicLinkRepository extends Repository implements PublicLinkReposit /** * Refreshes a public link * - * @param PublicLinkData $publicLinkData + * @param \SP\Domain\Account\Models\PublicLink $publicLinkData * * @return bool * @throws SPException * @throws ConstraintException * @throws QueryException */ - public function refresh(PublicLinkData $publicLinkData): bool + public function refresh(PublicLink $publicLinkData): bool { $query = $this->queryFactory ->newUpdate() diff --git a/lib/SP/Infrastructure/Auth/Repositories/AuthTokenRepository.php b/lib/SP/Infrastructure/Auth/Repositories/AuthTokenRepository.php index ed9572a7..485ecc2a 100644 --- a/lib/SP/Infrastructure/Auth/Repositories/AuthTokenRepository.php +++ b/lib/SP/Infrastructure/Auth/Repositories/AuthTokenRepository.php @@ -25,8 +25,8 @@ namespace SP\Infrastructure\Auth\Repositories; use Exception; -use SP\DataModel\AuthToken; use SP\DataModel\ItemSearchData; +use SP\Domain\Auth\Models\AuthToken; use SP\Domain\Auth\Ports\AuthTokenRepositoryInterface; use SP\Domain\Core\Exceptions\ConstraintException; use SP\Domain\Core\Exceptions\QueryException; diff --git a/lib/SP/Infrastructure/Database/QueryResult.php b/lib/SP/Infrastructure/Database/QueryResult.php index 91e83dc8..db722110 100644 --- a/lib/SP/Infrastructure/Database/QueryResult.php +++ b/lib/SP/Infrastructure/Database/QueryResult.php @@ -36,7 +36,10 @@ use function SP\__u; */ class QueryResult { - private ?array $data = null; + private ?array $data = null; + /** + * @var class-string|null $dataType + */ private ?string $dataType = null; private int $numRows = 0; private int $totalNumRows = 0; @@ -73,12 +76,10 @@ class QueryResult /** * @param class-string|null $dataType - * - * @return T|mixed|null - * + * @return T * @throws SPException */ - public function getData(?string $dataType = null): mixed + public function getData(?string $dataType = null): ?Model { $this->checkDataType($dataType); @@ -87,7 +88,6 @@ class QueryResult /** * @param string|null $dataType - * * @return void * @throws SPException */ diff --git a/lib/SP/Mvc/Controller/SimpleControllerHelper.php b/lib/SP/Mvc/Controller/SimpleControllerHelper.php index c6c1bbf7..35ea1e11 100644 --- a/lib/SP/Mvc/Controller/SimpleControllerHelper.php +++ b/lib/SP/Mvc/Controller/SimpleControllerHelper.php @@ -26,8 +26,8 @@ namespace SP\Mvc\Controller; use Klein\Klein; -use SP\Core\Acl\Acl; use SP\Core\PhpExtensionChecker; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\UI\ThemeInterface; use SP\Domain\Http\RequestInterface; @@ -38,14 +38,14 @@ final class SimpleControllerHelper { private ThemeInterface $theme; private Klein $router; - private Acl $acl; + private AclInterface $acl; private RequestInterface $request; private PhpExtensionChecker $extensionChecker; public function __construct( - ThemeInterface $theme, - Klein $router, - Acl $acl, + ThemeInterface $theme, + Klein $router, + AclInterface $acl, RequestInterface $request, PhpExtensionChecker $extensionChecker ) { @@ -66,7 +66,7 @@ final class SimpleControllerHelper return $this->router; } - public function getAcl(): Acl + public function getAcl(): AclInterface { return $this->acl; } diff --git a/lib/SP/Mvc/Controller/WebControllerHelper.php b/lib/SP/Mvc/Controller/WebControllerHelper.php index 8ff7c143..c619c88f 100644 --- a/lib/SP/Mvc/Controller/WebControllerHelper.php +++ b/lib/SP/Mvc/Controller/WebControllerHelper.php @@ -26,8 +26,8 @@ namespace SP\Mvc\Controller; use Klein\Klein; -use SP\Core\Acl\Acl; use SP\Core\PhpExtensionChecker; +use SP\Domain\Core\Acl\AclInterface; use SP\Domain\Core\UI\ThemeInterface; use SP\Domain\Http\RequestInterface; use SP\Modules\Web\Controllers\Helpers\LayoutHelper; @@ -41,7 +41,7 @@ final class WebControllerHelper { private ThemeInterface $theme; private Klein $router; - private Acl $acl; + private AclInterface $acl; private RequestInterface $request; private PhpExtensionChecker $extensionChecker; private TemplateInterface $template; @@ -50,9 +50,9 @@ final class WebControllerHelper public function __construct( SimpleControllerHelper $simpleControllerHelper, - TemplateInterface $template, + TemplateInterface $template, BrowserAuthInterface $browser, - LayoutHelper $layoutHelper + LayoutHelper $layoutHelper ) { $this->theme = $simpleControllerHelper->getTheme(); $this->router = $simpleControllerHelper->getRouter(); @@ -74,7 +74,7 @@ final class WebControllerHelper return $this->router; } - public function getAcl(): Acl + public function getAcl(): AclInterface { return $this->acl; } diff --git a/tests/SPT/Domain/Account/Services/PublicLinkServiceTest.php b/tests/SPT/Domain/Account/Services/PublicLinkServiceTest.php index 7e1babad..474e56de 100644 --- a/tests/SPT/Domain/Account/Services/PublicLinkServiceTest.php +++ b/tests/SPT/Domain/Account/Services/PublicLinkServiceTest.php @@ -29,7 +29,7 @@ use Defuse\Crypto\Exception\EnvironmentIsBrokenException; use PHPUnit\Framework\Constraint\Callback; use PHPUnit\Framework\MockObject\MockObject; use SP\DataModel\ItemSearchData; -use SP\DataModel\PublicLinkData; +use SP\Domain\Account\Models\PublicLink; use SP\Domain\Account\Ports\AccountServiceInterface; use SP\Domain\Account\Ports\PublicLinkRepositoryInterface; use SP\Domain\Account\Services\PublicLinkService; @@ -67,21 +67,20 @@ class PublicLinkServiceTest extends UnitaryTestCase */ public function testAddLinkView() { - $publicLinkData = new PublicLinkData(); - $publicLinkData->setHash(self::$faker->sha1); + $publicLink = new PublicLink(['hash' => self::$faker->sha1]); $this->publicLinkRepository ->expects(self::once()) ->method('addLinkView') ->with( - new Callback(function (PublicLinkData $publicLinkData) { + new Callback(function (PublicLink $publicLinkData) { $useInfo = unserialize($publicLinkData->getUseInfo(), ['allowed_classes' => false]); return is_array($useInfo) && count($useInfo) === 1; }) ); - $this->publicLinkService->addLinkView($publicLinkData); + $this->publicLinkService->addLinkView($publicLink); } /** @@ -91,7 +90,7 @@ class PublicLinkServiceTest extends UnitaryTestCase */ public function testAddLinkViewWithoutHash() { - $publicLinkData = new PublicLinkData(); + $publicLinkData = new PublicLink(); $this->expectException(ServiceException::class); $this->expectExceptionMessage('Public link hash not set'); @@ -106,30 +105,34 @@ class PublicLinkServiceTest extends UnitaryTestCase */ public function testAddLinkViewWithUseInfo() { - $publicLinkData = new PublicLinkData(); - $publicLinkData->setHash(self::$faker->sha1); - $publicLinkData->setUseInfo([ - [ - 'who' => self::$faker->ipv4, - 'time' => time(), - 'hash' => self::$faker->sha1, - 'agent' => self::$faker->userAgent, - 'https' => self::$faker->boolean, - ], - ]); + $properties = [ + 'useInfo' => serialize( + [ + [ + 'who' => self::$faker->ipv4, + 'time' => time(), + 'hash' => self::$faker->sha1, + 'agent' => self::$faker->userAgent, + 'https' => self::$faker->boolean, + ], + ] + ), + 'hash' => self::$faker->sha1 + ]; + $publicLink = new PublicLink($properties); $this->publicLinkRepository ->expects(self::once()) ->method('addLinkView') ->with( - new Callback(function (PublicLinkData $publicLinkData) { + new Callback(function (PublicLink $publicLinkData) { $useInfo = unserialize($publicLinkData->getUseInfo(), ['allowed_classes' => false]); return is_array($useInfo) && count($useInfo) === 2; }) ); - $this->publicLinkService->addLinkView($publicLinkData); + $this->publicLinkService->addLinkView($publicLink); } /** @@ -326,7 +329,7 @@ class PublicLinkServiceTest extends UnitaryTestCase ->expects(self::once()) ->method('refresh') ->with( - new Callback(function (PublicLinkData $actual) use ($publicLinkData) { + new Callback(function (PublicLink $actual) use ($publicLinkData) { $filter = ['hash', 'dateExpire', 'maxCountViews', 'data']; return $actual->toArray(null, $filter) === $publicLinkData->toArray(null, $filter) @@ -462,7 +465,7 @@ class PublicLinkServiceTest extends UnitaryTestCase $this->expectException(ServiceException::class); $this->expectExceptionMessage('Not implemented'); - $this->publicLinkService->getAllBasic(); + $this->publicLinkService->getAll(); } public function testGetUseInfo() @@ -517,7 +520,7 @@ class PublicLinkServiceTest extends UnitaryTestCase ->expects(self::once()) ->method('create') ->with( - new Callback(function (PublicLinkData $actual) use ($publicLinkData) { + new Callback(function (PublicLink $actual) use ($publicLinkData) { $filter = ['hash', 'dateExpire', 'maxCountViews', 'data']; return $actual->toArray(null, $filter) === $publicLinkData->toArray(null, $filter) diff --git a/tests/SPT/Domain/Api/Services/ApiServiceTest.php b/tests/SPT/Domain/Api/Services/ApiServiceTest.php index 83e6ec81..d69d32ab 100644 --- a/tests/SPT/Domain/Api/Services/ApiServiceTest.php +++ b/tests/SPT/Domain/Api/Services/ApiServiceTest.php @@ -31,9 +31,9 @@ use ReflectionClass; use SP\Core\Context\ContextException; use SP\Core\Crypt\Crypt; use SP\Core\Crypt\Vault; -use SP\DataModel\AuthToken; use SP\Domain\Api\Ports\ApiRequestInterface; use SP\Domain\Api\Services\ApiService; +use SP\Domain\Auth\Models\AuthToken; use SP\Domain\Auth\Ports\AuthTokenServiceInterface; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Core\Acl\AclActionsInterface; @@ -569,7 +569,7 @@ class ApiServiceTest extends UnitaryTestCase */ public function testRequireMasterPass() { - $actionId = self::$faker->randomNumber(); + $actionId = self::$faker->randomNumber(4); $authToken = self::$faker->password; $authTokenHash = password_hash($authToken, PASSWORD_BCRYPT); diff --git a/tests/SPT/Domain/Auth/Services/AuthTokenTest.php b/tests/SPT/Domain/Auth/Services/AuthTokenTest.php new file mode 100644 index 00000000..cf77cddb --- /dev/null +++ b/tests/SPT/Domain/Auth/Services/AuthTokenTest.php @@ -0,0 +1,645 @@ +. + */ + +namespace SPT\Domain\Auth\Services; + +use Defuse\Crypto\Exception\CryptoException; +use Defuse\Crypto\Exception\EnvironmentIsBrokenException; +use PHPUnit\Framework\Constraint\Callback; +use SP\Core\Context\ContextException; +use SP\Domain\Auth\Models\AuthToken as AuthTokenModel; +use SP\Domain\Auth\Ports\AuthTokenRepositoryInterface; +use SP\Domain\Auth\Services\AuthToken; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Core\Acl\AclActionsInterface; +use SP\Domain\Core\Crypt\CryptInterface; +use SP\Domain\Core\Exceptions\ConstraintException; +use SP\Domain\Core\Exceptions\CryptException; +use SP\Domain\Core\Exceptions\QueryException; +use SP\Domain\Core\Exceptions\SPException; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SPT\Generators\AuthTokenGenerator; +use SPT\Generators\ItemSearchDataGenerator; +use SPT\UnitaryTestCase; + +/** + * Class AuthTokenTest + * + * @group unitary + */ +class AuthTokenTest extends UnitaryTestCase +{ + + private AuthTokenRepositoryInterface|\PHPUnit\Framework\MockObject\MockObject $authTokenRepository; + private CryptInterface|\PHPUnit\Framework\MockObject\MockObject $crypt; + private AuthToken $authToken; + + public static function secureActionDataProvider(): array + { + return [ + [AclActionsInterface::ACCOUNT_VIEW_PASS], + [AclActionsInterface::ACCOUNT_EDIT_PASS], + [AclActionsInterface::ACCOUNT_CREATE], + [AclActionsInterface::ACCOUNT_VIEW], + [AclActionsInterface::CATEGORY_VIEW], + [AclActionsInterface::CLIENT_VIEW], + ]; + } + + /** + * @throws ConstraintException + * @throws QueryException + * @throws ServiceException + */ + public function testDeleteByIdBatch() + { + $ids = array_map(fn() => self::$faker->randomNumber(), range(0, 4)); + + $queryResult = new QueryResult(); + $queryResult->setAffectedNumRows(1); + + $this->authTokenRepository + ->expects(self::once()) + ->method('deleteByIdBatch') + ->with($ids) + ->willReturn($queryResult); + + $this->authToken->deleteByIdBatch($ids); + } + + /** + * @throws ServiceException + * @throws SPException + */ + public function testDeleteByIdBatchError() + { + $ids = array_map(fn() => self::$faker->randomNumber(), range(0, 4)); + + $queryResult = new QueryResult(); + $queryResult->setAffectedNumRows(0); + + $this->authTokenRepository + ->expects(self::once()) + ->method('deleteByIdBatch') + ->with($ids) + ->willReturn($queryResult); + + $this->expectException(ServiceException::class); + $this->expectExceptionMessage('Error while removing the tokens'); + + $this->authToken->deleteByIdBatch($ids); + } + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function testSearch() + { + $itemSearch = ItemSearchDataGenerator::factory()->buildItemSearchData(); + + $this->authTokenRepository + ->expects(self::once()) + ->method('search') + ->with($itemSearch); + + $this->authToken->search($itemSearch); + } + + /** + * @throws ConstraintException + * @throws CryptoException + * @throws EnvironmentIsBrokenException + * @throws SPException + * @throws QueryException + */ + public function testCreateWithExistingToken() + { + $authToken = AuthTokenGenerator::factory()->buildAuthToken(); + + $this->authTokenRepository + ->expects(self::once()) + ->method('getTokenByUserId') + ->with($authToken->getUserId()) + ->willReturn(new QueryResult([$authToken])); + + $queryResult = new QueryResult([]); + $queryResult->setLastId(100); + + $this->authTokenRepository + ->expects(self::once()) + ->method('create') + ->with( + new Callback(function (AuthTokenModel $current) use ($authToken) { + return $current->getId() === $authToken->getId() + && $current->getUserId() === $authToken->getUserId() + && $current->getStartDate() === $authToken->getStartDate() + && $current->getActionId() === $authToken->getActionId() + && $current->getVault() === $authToken->getVault() + && $current->getToken() === $authToken->getToken() + && $current->getHash() === null + && $current->getCreatedBy() === $this->context->getUserData()->getId(); + }) + ) + ->willReturn($queryResult); + + $out = $this->authToken->create($authToken); + + $this->assertEquals(100, $out); + } + + /** + * @throws ConstraintException + * @throws CryptoException + * @throws EnvironmentIsBrokenException + * @throws SPException + * @throws QueryException + */ + public function testCreateWithNoExistingToken() + { + $authToken = AuthTokenGenerator::factory()->buildAuthToken(); + + $this->authTokenRepository + ->expects(self::once()) + ->method('getTokenByUserId') + ->with($authToken->getUserId()) + ->willReturn(new QueryResult([])); + + $queryResult = new QueryResult([]); + $queryResult->setLastId(100); + + $this->authTokenRepository + ->expects(self::once()) + ->method('create') + ->with( + new Callback(function (AuthTokenModel $current) use ($authToken) { + return $current->getId() === $authToken->getId() + && $current->getUserId() === $authToken->getUserId() + && $current->getStartDate() === $authToken->getStartDate() + && $current->getActionId() === $authToken->getActionId() + && $current->getVault() === $authToken->getVault() + && $current->getToken() !== $authToken->getToken() + && $current->getHash() === null + && $current->getCreatedBy() === $this->context->getUserData()->getId(); + }) + ) + ->willReturn($queryResult); + + $out = $this->authToken->create($authToken); + + $this->assertEquals(100, $out); + } + + /** + * @dataProvider secureActionDataProvider + * @param int $action + * @throws ConstraintException + * @throws CryptoException + * @throws EnvironmentIsBrokenException + * @throws QueryException + * @throws SPException + * @throws ContextException + */ + public function testCreateWithSecureAction(int $action) + { + $this->context->setTrasientKey('_masterpass', 'test_pass'); + + $authToken = AuthTokenGenerator::factory()->buildAuthToken()->mutate(['actionId' => $action]); + + $this->authTokenRepository + ->expects(self::once()) + ->method('getTokenByUserId') + ->with($authToken->getUserId()) + ->willReturn(new QueryResult([$authToken])); + + $queryResult = new QueryResult([]); + $queryResult->setLastId(100); + + $this->authTokenRepository + ->expects(self::once()) + ->method('create') + ->with( + new Callback(function (AuthTokenModel $current) use ($authToken) { + return $current->getId() === $authToken->getId() + && $current->getUserId() === $authToken->getUserId() + && $current->getStartDate() === $authToken->getStartDate() + && $current->getActionId() === $authToken->getActionId() + && $current->getToken() === $authToken->getToken() + && $current->getVault() !== $authToken->getVault() + && $current->getHash() !== $authToken->getHash() + && $current->getCreatedBy() === $this->context->getUserData()->getId(); + }) + ) + ->willReturn($queryResult); + + $password = $authToken->getHash() . $authToken->getToken(); + + $this->crypt + ->expects(self::once()) + ->method('makeSecuredKey') + ->with($password) + ->willReturn('key'); + + $this->crypt + ->expects(self::once()) + ->method('encrypt') + ->with('test_pass', 'key', $password) + ->willReturn('secure_data'); + + $out = $this->authToken->create($authToken); + + $this->assertEquals(100, $out); + } + + /** + * @throws ConstraintException + * @throws SPException + * @throws QueryException + */ + public function testUpdateRaw() + { + $authToken = AuthTokenGenerator::factory()->buildAuthToken(); + + $this->authTokenRepository + ->expects(self::once()) + ->method('update') + ->with($authToken); + + $this->authToken->updateRaw($authToken); + } + + /** + * @throws NoSuchItemException + * @throws ConstraintException + * @throws QueryException + * @throws SPException + */ + public function testGetTokenByToken() + { + $authToken = AuthTokenGenerator::factory()->buildAuthToken(); + + $this->authTokenRepository + ->expects(self::once()) + ->method('getTokenByToken') + ->with($authToken->getActionId(), $authToken->getToken()) + ->willReturn(new QueryResult([$authToken])); + + $out = $this->authToken->getTokenByToken($authToken->getActionId(), $authToken->getToken()); + + $this->assertEquals($authToken, $out); + } + + /** + * @throws NoSuchItemException + * @throws ConstraintException + * @throws QueryException + * @throws SPException + */ + public function testGetTokenByTokenWithNoFound() + { + $authToken = AuthTokenGenerator::factory()->buildAuthToken(); + + $this->authTokenRepository + ->expects(self::once()) + ->method('getTokenByToken') + ->with($authToken->getActionId(), $authToken->getToken()) + ->willReturn(new QueryResult([])); + + $this->expectException(NoSuchItemException::class); + $this->expectExceptionMessage('Token not found'); + + $this->authToken->getTokenByToken($authToken->getActionId(), $authToken->getToken()); + } + + /** + * @throws CryptException + * @throws SPException + * @throws QueryException + * @throws EnvironmentIsBrokenException + * @throws ServiceException + * @throws DuplicatedItemException + * @throws ConstraintException + */ + public function testUpdate() + { + $authToken = AuthTokenGenerator::factory()->buildAuthToken(); + + $this->authTokenRepository + ->expects(self::once()) + ->method('getTokenByUserId') + ->with($authToken->getUserId()) + ->willReturn(new QueryResult([$authToken])); + + $this->authTokenRepository + ->expects(self::once()) + ->method('update') + ->with( + new Callback(function (AuthTokenModel $current) use ($authToken) { + return $current->getId() === $authToken->getId() + && $current->getUserId() === $authToken->getUserId() + && $current->getStartDate() === $authToken->getStartDate() + && $current->getActionId() === $authToken->getActionId() + && $current->getVault() === $authToken->getVault() + && $current->getToken() === $authToken->getToken() + && $current->getHash() === null + && $current->getCreatedBy() === $this->context->getUserData()->getId(); + }) + ) + ->willReturn(true); + + $this->authToken->update($authToken); + } + + /** + * @throws ConstraintException + * @throws CryptoException + * @throws EnvironmentIsBrokenException + * @throws SPException + * @throws QueryException + */ + public function testUpdateWithNoExistingToken() + { + $authToken = AuthTokenGenerator::factory()->buildAuthToken(); + + $this->authTokenRepository + ->expects(self::once()) + ->method('getTokenByUserId') + ->with($authToken->getUserId()) + ->willReturn(new QueryResult([])); + + $this->authTokenRepository + ->expects(self::once()) + ->method('update') + ->with( + new Callback(function (AuthTokenModel $current) use ($authToken) { + return $current->getId() === $authToken->getId() + && $current->getUserId() === $authToken->getUserId() + && $current->getStartDate() === $authToken->getStartDate() + && $current->getActionId() === $authToken->getActionId() + && $current->getVault() === $authToken->getVault() + && $current->getToken() !== $authToken->getToken() + && $current->getHash() === null + && $current->getCreatedBy() === $this->context->getUserData()->getId(); + }) + ) + ->willReturn(true); + + $this->authToken->update($authToken); + } + + /** + * @dataProvider secureActionDataProvider + * @param int $action + * @throws ConstraintException + * @throws CryptoException + * @throws EnvironmentIsBrokenException + * @throws QueryException + * @throws SPException + * @throws ContextException + */ + public function testUpdateWithSecureAction(int $action) + { + $this->context->setTrasientKey('_masterpass', 'test_pass'); + + $authToken = AuthTokenGenerator::factory()->buildAuthToken()->mutate(['actionId' => $action]); + + $this->authTokenRepository + ->expects(self::once()) + ->method('getTokenByUserId') + ->with($authToken->getUserId()) + ->willReturn(new QueryResult([$authToken])); + + $queryResult = new QueryResult([]); + $queryResult->setLastId(100); + + $this->authTokenRepository + ->expects(self::once()) + ->method('update') + ->with( + new Callback(function (AuthTokenModel $current) use ($authToken) { + return $current->getId() === $authToken->getId() + && $current->getUserId() === $authToken->getUserId() + && $current->getStartDate() === $authToken->getStartDate() + && $current->getActionId() === $authToken->getActionId() + && $current->getToken() === $authToken->getToken() + && $current->getVault() !== $authToken->getVault() + && $current->getHash() !== $authToken->getHash() + && $current->getCreatedBy() === $this->context->getUserData()->getId(); + }) + ) + ->willReturn(true); + + $password = $authToken->getHash() . $authToken->getToken(); + + $this->crypt + ->expects(self::once()) + ->method('makeSecuredKey') + ->with($password) + ->willReturn('key'); + + $this->crypt + ->expects(self::once()) + ->method('encrypt') + ->with('test_pass', 'key', $password) + ->willReturn('secure_data'); + + $this->authToken->update($authToken); + } + + /** + * @throws ConstraintException + * @throws SPException + * @throws QueryException + */ + public function testGetById() + { + $id = self::$faker->randomNumber(); + + $authToken = AuthTokenGenerator::factory()->buildAuthToken(); + + $this->authTokenRepository + ->expects(self::once()) + ->method('getById') + ->with($id) + ->willReturn(new QueryResult([$authToken])); + + $out = $this->authToken->getById($id); + + $this->assertEquals($authToken, $out); + } + + /** + * @throws ConstraintException + * @throws SPException + * @throws QueryException + */ + public function testGetAll() + { + $authToken = AuthTokenGenerator::factory()->buildAuthToken(); + + $this->authTokenRepository + ->expects(self::once()) + ->method('getAll') + ->willReturn(new QueryResult([$authToken])); + + $out = $this->authToken->getAll(); + + $this->assertEquals([$authToken], $out); + } + + /** + * @throws ConstraintException + * @throws NoSuchItemException + * @throws QueryException + */ + public function testDelete() + { + $id = self::$faker->randomNumber(); + + $queryResult = new QueryResult([1]); + $queryResult->setAffectedNumRows(1); + + $this->authTokenRepository + ->expects(self::once()) + ->method('delete') + ->with($id) + ->willReturn($queryResult); + + $this->authToken->delete($id); + } + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function testDeleteWithNotFound() + { + $id = self::$faker->randomNumber(); + + $this->authTokenRepository + ->expects(self::once()) + ->method('delete') + ->with($id) + ->willReturn(new QueryResult([])); + + $this->expectException(NoSuchItemException::class); + $this->expectExceptionMessage('Token not found'); + + $this->authToken->delete($id); + } + + /** + * @throws ContextException + * @throws \Exception + */ + public function testRefreshAndUpdate() + { + $this->context->setTrasientKey('_masterpass', 'test_pass'); + + $authToken = AuthTokenGenerator::factory()->buildAuthToken(); + + $this->authTokenRepository + ->expects(self::never()) + ->method('getTokenByUserId'); + + $this->authTokenRepository + ->expects(self::once()) + ->method('transactionAware') + ->with( + new Callback(function (callable $callable) use ($authToken) { + $callable(); + return true; + }) + ) + ->willReturn(true); + + $this->authTokenRepository + ->expects(self::once()) + ->method('refreshTokenByUserId') + ->with( + $authToken->getUserId(), + new Callback(function (string $token) use ($authToken) { + return $token !== $authToken->getToken(); + }) + ); + + $this->authTokenRepository + ->expects(self::once()) + ->method('refreshVaultByUserId') + ->with( + $authToken->getUserId(), + new Callback(function (string $vault) use ($authToken) { + return $vault !== $authToken->getVault(); + }), + new Callback(function (string $hash) use ($authToken) { + return $hash !== $authToken->getHash(); + }) + ); + + $this->crypt + ->expects(self::once()) + ->method('makeSecuredKey') + ->with(self::anything()) + ->willReturn('key'); + + $this->crypt + ->expects(self::once()) + ->method('encrypt') + ->with('test_pass', 'key', self::anything()) + ->willReturn('secure_data'); + + $this->authTokenRepository + ->expects(self::once()) + ->method('update') + ->with( + new Callback(function (AuthTokenModel $current) use ($authToken) { + return $current->getId() === $authToken->getId() + && $current->getUserId() === $authToken->getUserId() + && $current->getStartDate() === $authToken->getStartDate() + && $current->getActionId() === $authToken->getActionId() + && $current->getVault() === $authToken->getVault() + && $current->getToken() !== $authToken->getToken() + && $current->getHash() === null + && $current->getCreatedBy() === $this->context->getUserData()->getId(); + }) + ) + ->willReturn(true); + + $this->authToken->refreshAndUpdate($authToken); + } + + protected function setUp(): void + { + parent::setUp(); + + $this->authTokenRepository = $this->createMock(AuthTokenRepositoryInterface::class); + $this->crypt = $this->createMock(CryptInterface::class); + + $this->authToken = new AuthToken($this->application, $this->authTokenRepository, $this->crypt); + } + + +} diff --git a/tests/SPT/Domain/Export/Services/FileBackupServiceTest.php b/tests/SPT/Domain/Export/Services/FileBackupServiceTest.php index 5c84994a..33cc2c6f 100644 --- a/tests/SPT/Domain/Export/Services/FileBackupServiceTest.php +++ b/tests/SPT/Domain/Export/Services/FileBackupServiceTest.php @@ -30,6 +30,7 @@ use PHPUnit\Framework\Constraint\Callback; use PHPUnit\Framework\MockObject\Exception; use PHPUnit\Framework\MockObject\MockObject; use SP\Core\Context\ContextException; +use SP\Domain\Common\Models\Simple; use SP\Domain\Common\Services\ServiceException; use SP\Domain\Core\Exceptions\SPException; use SP\Domain\Export\Ports\BackupFilesInterface; @@ -43,7 +44,6 @@ use SP\Infrastructure\File\ArchiveHandlerInterface; use SP\Infrastructure\File\FileException; use SP\Infrastructure\File\FileHandlerInterface; use SPT\UnitaryTestCase; -use stdClass; /** * Class FileBackupServiceTest @@ -158,7 +158,7 @@ class FileBackupServiceTest extends UnitaryTestCase private function buildCreateResult(string $type): QueryResult { - $data = new StdClass(); + $data = new Simple(); switch ($type) { case 'table': diff --git a/tests/SPT/Generators/AccountDataGenerator.php b/tests/SPT/Generators/AccountDataGenerator.php index afcc9009..45b252e6 100644 --- a/tests/SPT/Generators/AccountDataGenerator.php +++ b/tests/SPT/Generators/AccountDataGenerator.php @@ -30,7 +30,7 @@ use SP\Domain\Account\Dtos\AccountEnrichedDto; 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\AccountView; use SP\Domain\Account\Models\AccountSearchView; use SP\Domain\Common\Models\Simple; @@ -48,9 +48,9 @@ final class AccountDataGenerator extends DataGenerator return $out->withUserGroups($this->buildItemData()); } - public function buildAccountDataView(): AccountDataView + public function buildAccountDataView(): AccountView { - return new AccountDataView($this->getAccountProperties()); + return new AccountView($this->getAccountProperties()); } /** diff --git a/tests/SPT/Generators/AuthTokenGenerator.php b/tests/SPT/Generators/AuthTokenGenerator.php index 1b7d230d..5a5ada56 100644 --- a/tests/SPT/Generators/AuthTokenGenerator.php +++ b/tests/SPT/Generators/AuthTokenGenerator.php @@ -26,7 +26,7 @@ namespace SPT\Generators; use SP\Core\Crypt\Crypt; use SP\Core\Crypt\Vault; -use SP\DataModel\AuthToken; +use SP\Domain\Auth\Models\AuthToken; use SP\Domain\Core\Exceptions\CryptException; /** @@ -47,7 +47,7 @@ final class AuthTokenGenerator extends DataGenerator 'token' => $this->faker->sha1(), 'createdBy' => $this->faker->randomNumber(), 'startDate' => $this->faker->unixTime(), - 'actionId' => $this->faker->randomNumber(), + 'actionId' => $this->faker->randomNumber(4), 'hash' => $this->faker->sha1(), 'vault' => serialize($this->getVault()) ]; @@ -56,7 +56,7 @@ final class AuthTokenGenerator extends DataGenerator private function getVault(): ?Vault { try { - return Vault::factory(new Crypt())->saveData($this->faker->text(), $this->faker->text); + return Vault::factory(new Crypt())->saveData($this->faker->text(), $this->faker->sha1()); } catch (CryptException) { return null; } diff --git a/tests/SPT/Generators/PublicLinkDataGenerator.php b/tests/SPT/Generators/PublicLinkDataGenerator.php index 86a0648f..e32c4f08 100644 --- a/tests/SPT/Generators/PublicLinkDataGenerator.php +++ b/tests/SPT/Generators/PublicLinkDataGenerator.php @@ -24,17 +24,17 @@ namespace SPT\Generators; -use SP\DataModel\PublicLinkData; -use SP\DataModel\PublicLinkListData; +use SP\DataModel\PublicLinkList; +use SP\Domain\Account\Models\PublicLink; /** * Class PublicLinkDataGenerator */ final class PublicLinkDataGenerator extends DataGenerator { - public function buildPublicLink(): PublicLinkData + public function buildPublicLink(): PublicLink { - return new PublicLinkData($this->getPublicLinkProperties()); + return new PublicLink($this->getPublicLinkProperties()); } private function getPublicLinkProperties(): array @@ -71,9 +71,9 @@ final class PublicLinkDataGenerator extends DataGenerator ); } - public function buildPublicLinkList(): PublicLinkListData + public function buildPublicLinkList(): PublicLinkList { - return new PublicLinkListData( + return new PublicLinkList( array_merge($this->getPublicLinkProperties(), [ 'userName' => $this->faker->name, 'userLogin' => $this->faker->userName, diff --git a/tests/SPT/Infrastructure/Account/Repositories/AccountRepositoryTest.php b/tests/SPT/Infrastructure/Account/Repositories/AccountRepositoryTest.php index 52c25353..2b211950 100644 --- a/tests/SPT/Infrastructure/Account/Repositories/AccountRepositoryTest.php +++ b/tests/SPT/Infrastructure/Account/Repositories/AccountRepositoryTest.php @@ -30,7 +30,7 @@ use PHPUnit\Framework\MockObject\MockObject; use SP\DataModel\ItemSearchData; use SP\Domain\Account\Dtos\EncryptedPassword; use SP\Domain\Account\Models\Account; -use SP\Domain\Account\Models\AccountDataView; +use SP\Domain\Account\Models\AccountView; use SP\Domain\Account\Models\AccountSearchView; use SP\Domain\Account\Ports\AccountFilterUserInterface; use SP\Domain\Common\Models\Simple; @@ -578,7 +578,7 @@ class AccountRepositoryTest extends UnitaryTestCase return count($params) === 1 && $params['id'] === $id - && $arg->getMapClassName() === AccountDataView::class + && $arg->getMapClassName() === AccountView::class && !empty($arg->getQuery()->getStatement()); } ); diff --git a/tests/SPT/Infrastructure/Account/Repositories/PublicLinkRepositoryTest.php b/tests/SPT/Infrastructure/Account/Repositories/PublicLinkRepositoryTest.php index 80f5fcc9..f65feb5c 100644 --- a/tests/SPT/Infrastructure/Account/Repositories/PublicLinkRepositoryTest.php +++ b/tests/SPT/Infrastructure/Account/Repositories/PublicLinkRepositoryTest.php @@ -28,7 +28,7 @@ use Aura\SqlQuery\QueryFactory; use PHPUnit\Framework\Constraint\Callback; use PHPUnit\Framework\MockObject\MockObject; use SP\DataModel\ItemSearchData; -use SP\DataModel\PublicLinkData; +use SP\Domain\Account\Models\PublicLink; use SP\Domain\Common\Models\Simple; use SP\Domain\Core\Exceptions\ConstraintException; use SP\Domain\Core\Exceptions\QueryException; @@ -172,7 +172,7 @@ class PublicLinkRepositoryTest extends UnitaryTestCase $this->assertTrue($this->publicLinkRepository->addLinkView($publicLinkData)); } - private function buildPublicLinkData(): PublicLinkData + private function buildPublicLinkData(): PublicLink { $data = [ 'id' => self::$faker->randomNumber(), @@ -191,7 +191,7 @@ class PublicLinkRepositoryTest extends UnitaryTestCase 'data' => self::$faker->text(), ]; - return new PublicLinkData($data); + return new PublicLink($data); } /** diff --git a/tests/SPT/Infrastructure/Auth/Repositories/AuthTokenRepositoryTest.php b/tests/SPT/Infrastructure/Auth/Repositories/AuthTokenRepositoryTest.php index 7f29d933..10b1e9a5 100644 --- a/tests/SPT/Infrastructure/Auth/Repositories/AuthTokenRepositoryTest.php +++ b/tests/SPT/Infrastructure/Auth/Repositories/AuthTokenRepositoryTest.php @@ -31,8 +31,8 @@ use Aura\SqlQuery\Common\UpdateInterface; use Aura\SqlQuery\QueryFactory; use PHPUnit\Framework\Constraint\Callback; use PHPUnit\Framework\MockObject\MockObject; -use SP\DataModel\AuthToken; use SP\DataModel\ItemSearchData; +use SP\Domain\Auth\Models\AuthToken; use SP\Domain\Common\Models\Simple; use SP\Domain\Core\Exceptions\ConstraintException; use SP\Domain\Core\Exceptions\QueryException; diff --git a/tests/SPT/Modules/Api/ApiTestCase.php b/tests/SPT/Modules/Api/ApiTestCase.php index 6ae2d275..759e4cb0 100644 --- a/tests/SPT/Modules/Api/ApiTestCase.php +++ b/tests/SPT/Modules/Api/ApiTestCase.php @@ -38,9 +38,9 @@ use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use RuntimeException; use SP\Core\Bootstrap\BootstrapApi; -use SP\DataModel\AuthToken; use SP\Domain\Api\Services\ApiRequest; -use SP\Domain\Auth\Services\AuthTokenService; +use SP\Domain\Auth\Models\AuthToken; +use SP\Domain\Auth\Services\AuthToken; use SP\Domain\Config\Ports\ConfigDataInterface; use SP\Domain\Config\Ports\ConfigInterface; use SP\Domain\Core\Acl\AclActionsInterface; @@ -145,7 +145,7 @@ abstract class ApiTestCase extends TestCase [ ApiRequest::class => function (ContainerInterface $c) use ($actionId, $params) { $token = self::createApiToken( - $c->get(AuthTokenService::class), + $c->get(AuthToken::class), $actionId ); @@ -224,8 +224,8 @@ abstract class ApiTestCase extends TestCase * @throws SPException */ private static function createApiToken( - AuthTokenService $service, - int $actionId + AuthToken $service, + int $actionId ): AuthToken { $data = new AuthToken(); diff --git a/tests/SPT/Repositories/AccountFileRepositoryTest.php b/tests/SPT/Repositories/AccountFileRepositoryTest.php deleted file mode 100644 index 181693a0..00000000 --- a/tests/SPT/Repositories/AccountFileRepositoryTest.php +++ /dev/null @@ -1,309 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\FileData; -use SP\DataModel\FileExtData; -use SP\DataModel\ItemSearchData; -use SP\Domain\Account\Ports\AccountFileRepositoryInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Infrastructure\Account\Repositories\AccountFileRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class AccountFileRepositoryTest - * - * @package SPT\Repositories - */ -class AccountFileRepositoryTest extends DatabaseTestCase -{ - /** - * @var AccountFileRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(AccountFileRepository::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDelete() - { - $this->assertEquals(1, self::$repository->delete(1)); - $this->assertEquals(1, self::$repository->delete(3)); - $this->assertEquals(0, self::$repository->delete(10)); - - $this->assertEquals(1, self::getRowCount('AccountFile')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(2, self::$repository->deleteByIdBatch([1, 3, 10])); - $this->assertEquals(0, self::$repository->deleteByIdBatch([])); - - $this->assertEquals(1, self::getRowCount('AccountFile')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetInfoById() - { - $result = self::$repository->getInfoById(1); - /** @var FileExtData $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(FileExtData::class, $data); - $this->assertEquals('sysPass.xml', $data->getName()); - $this->assertEquals('text/xml', $data->getType()); - $this->assertEquals('XML', $data->getExtension()); - $this->assertEquals('Google', $data->getAccountName()); - $this->assertEquals('Google', $data->getClientName()); - $this->assertEquals(1312, $data->getSize()); - $this->assertEquals(1, $data->getAccountId()); - $this->assertNull($data->getContent()); - $this->assertNull($data->getThumb()); - - $result = self::$repository->getInfoById(10); - - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $result = self::$repository->getById(1); - /** @var FileExtData $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(FileExtData::class, $data); - $this->assertEquals('sysPass.xml', $data->getName()); - $this->assertEquals('text/xml', $data->getType()); - $this->assertEquals('XML', $data->getExtension()); - $this->assertEquals('Google', $data->getAccountName()); - $this->assertEquals('Google', $data->getClientName()); - $this->assertEquals(1312, $data->getSize()); - $this->assertEquals(1, $data->getAccountId()); - $this->assertEquals(pack('H*', '3C3F786D6C2076657273696F6E3D22312E302220656E636F64696E673D225554462D38223F3E0A3C526F6F743E0A20203C4D6574613E0A202020203C47656E657261746F723E737973506173733C2F47656E657261746F723E0A202020203C56657273696F6E3E312E322E303C2F56657273696F6E3E0A202020203C54696D653E313433393332353330343C2F54696D653E0A202020203C557365722069643D2231223E61646D696E3C2F557365723E0A202020203C47726F75702069643D2231223E41646D696E733C2F47726F75703E0A202020203C486173683E36646232633238323731393136326630663136316531343731653734636531623C2F486173683E0A20203C2F4D6574613E0A20203C43617465676F726965733E0A202020203C43617465676F72792069643D2231223E0A2020202020203C6E616D653E485454503C2F6E616D653E0A2020202020203C6465736372697074696F6E2F3E0A202020203C2F43617465676F72793E0A20203C2F43617465676F726965733E0A20203C437573746F6D6572733E0A202020203C437573746F6D65722069643D2231223E0A2020202020203C6E616D653E476F6F676C6520496E632E3C2F6E616D653E0A2020202020203C6465736372697074696F6E2F3E0A202020203C2F437573746F6D65723E0A202020203C437573746F6D65722069643D2232223E0A2020202020203C6E616D653E4D6963726F736F667420496E633C2F6E616D653E0A2020202020203C6465736372697074696F6E2F3E0A202020203C2F437573746F6D65723E0A20203C2F437573746F6D6572733E0A20203C4163636F756E74733E0A202020203C4163636F756E742069643D2231223E0A2020202020203C6E616D653E476F6F676C653C2F6E616D653E0A2020202020203C637573746F6D657249643E313C2F637573746F6D657249643E0A2020202020203C63617465676F727949643E313C2F63617465676F727949643E0A2020202020203C6C6F67696E3E61646D696E3C2F6C6F67696E3E0A2020202020203C75726C3E382E382E382E383C2F75726C3E0A2020202020203C6E6F7465732F3E0A2020202020203C706173733E6C4E66513133634B6A384D592B79434F346652536B4773494334357247454C442F424E69345654614671593D3C2F706173733E0A2020202020203C7061737369763E454E6354743338503265346C643350395A553241767939664C466277386C42473947382F75414D785A6D343D3C2F7061737369763E0A202020203C2F4163636F756E743E0A202020203C4163636F756E742069643D2232223E0A2020202020203C6E616D653E4D6963726F736F66743C2F6E616D653E0A2020202020203C637573746F6D657249643E323C2F637573746F6D657249643E0A2020202020203C63617465676F727949643E313C2F63617465676F727949643E0A2020202020203C6C6F67696E3E726F6F743C2F6C6F67696E3E0A2020202020203C75726C3E342E342E342E343C2F75726C3E0A2020202020203C6E6F7465733E4E6F746173206465206D6963726F66736F66743C2F6E6F7465733E0A2020202020203C706173733E3352394F48632B53335A4E56684D795948352F784C476C76625246662F5367573348527261322B325349453D3C2F706173733E0A2020202020203C7061737369763E763637306A596B43547178635332344C4F65453077672B304330376A734C2F4635342B6E56484963544F773D3C2F7061737369763E0A202020203C2F4163636F756E743E0A20203C2F4163636F756E74733E0A3C2F526F6F743E0A'), $data->getContent()); - $this->assertEquals(pack('H*', '6E6F5F7468756D62'), $data->getThumb()); - - $result = self::$repository->getById(4); - /** @var FileExtData $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(FileExtData::class, $data); - $this->assertEquals('android.png', $data->getName()); - $this->assertEquals('image/png', $data->getType()); - $this->assertEquals('PNG', $data->getExtension()); - $this->assertEquals('Google', $data->getAccountName()); - $this->assertEquals('Google', $data->getClientName()); - $this->assertEquals(4295, $data->getSize()); - $this->assertEquals(1, $data->getAccountId()); - $this->assertEquals(pack('H*', '89504E470D0A1A0A0000000D4948445200000080000000800806000000C33E61CB00000006624B474400FF00FF00FFA0BDA793000000097048597300000B1300000B1301009A9C180000000774494D4507DD011D0E180BE2306F78000010544944415478DAED5D6B745CD575FEBE7DEFC8961F3C0C01EC45480C2B8B0026A1D4206B2CB9C27181F208D074816D59069A16280B92A6246D42520A252D210FD2248426818418C9C63CD264C182BAE1154B1A4960CAB35E506A1E5D26501C9E768464CDDCF3F5C7BDA31796A59135F28CE66C2D594B9A19DF73F7FECEB71F67DF7388329096CCC293C1E997845174D1F2FACE374B7DBCCD1B17CF0F42DDDB1BED58F2E74B9E7DBB94C76AE5000069DA05A2CE8CA8EF94FA587FF6507D1503D71A018757D9EC334A7DBC650100B2E79F4C70B0E0336B338BFEA494C75A352DF70D1AE71AB8F9A5F51DCD1E001320AB163FB159C2CD12663A58D35D1DE9D9A538CE350F351C65C6931D1038B9CBAFBA11F200983016705F96DC9B3077CE4EC7926481B0BAF7F208760C22AD69AAEBEC2A07BD960D001AD39DBF27832F986C3A694DEBDA4F9A5352816A5BC332293CD790450AE115E5A2D7B201000050D10310FE57CC9DEAD47342A98CEBB6473E5585A0F72C3077805C78EDF2FAB6B7CA46A7283359DB9E5E2D6A0DA42E9B3E73C9CA850F6547FBCCBAB69A1991719E219C0146F38420A07400E40218009102BA01F70E2D34C1BD48177457F76CDFF6A7CB9ECE8D9AF6B5A76B403C4CEA8528179D76FE92C75E2F177D86E5060089F793DC08CBFD91EBED5905E0D6E1EFB9E7D7A7A5B6CFD85E47BAE3011C23E02002F300CD00381750086086C86133C0DE8364005E045C774FF5CCDFB574A4B7105107A2E0A5C6FA8EA7771D9FE07A11339C70533919BF2C1900009ADBEACE27A31F928E3DCF1FB5EF5F7CF6E7B907375F17BCF6EE7D75845B29E3498110413A5C4415101B5A1020825072E79404821093BF0CFC4100084A10F09E889728E668EE2E58EFFAC69A27B702C0DAAE450B11059B003D09F0338D8B332F7B004C46D09549B782564FD7773314DE01E3B7441C09A91A04094862FC1322C971F14DE21E10A3062024800ECEDD1B657139A6A183C0C141C4BF5B59DFF1BD72D3A3952B00E8EC3B0E511616FCA5026D70D47110A69348883DB139314EE327E44E80313DC43F6240848E38C7A6BB570D3CCCC4E742CDBCBB2CF5586E035ED75A77906374BA8C5F20B9801A740F1404F6D379516290D871C47048CA3CA2EBA37827841FCEDEE785473FFD8937E5015014DAAF3D9BB02F89AA0110304FC87BF12E84FC10040ADB40AC0F72D13F2F5FF2E81B1E0013286B3A177D3E10AF226C7FF4CF7A09E4DEBD07C59C80981048E07527BD2EBAAFAF4E77FDD203604F23FE478EFF10AAAAEE27834F00AAA228F183095C09E5A94E8441B683DCF9DDC6F4A67FF000182FE5B72F3A8EC0DD8E7604291156168C250146413038E46E545FF4E5D50D9BBA7D1650C8CC6FAF6D20C33B6176841162A2D2B2F0AB141C28C081B2CB2C0C7FBCB6ADE610CF00632EF4D42E03ED76331D085122588E050B498A07EE08173E9072D59F3D77C9035B3D03EC2ED8EB38611189663377A0627F3AC4F8FD2CA0815F94285B93481071553119811497103198A394142008C004BA3FDE99DA7E434BF3D98107C0483EBFB5EEE32985FF06E21080026803D9769EB20827C9D14114639A158C2439192088314711A2E8E020231C1947A7FDC3CDC3564412B352C1593AFCB59B3C007635F3DB3FB91F037C3F6270485C6461BE82C7FE843B9E66204593DD41B15E2E3C09D4CD4E8AE2A430FFAEE2794D4104B25BA19D17059C51A75C7635113DDBBFA4306400C99F62F0A608BB706D7BFA2B3E06F84091E7C46B81F06BCC2B99C290544F8098706EE4AE6BAA7FF4CA217143E6842B89F01A9261D18286643549E4EB51A4D3CEAFEF782AFFD2ADBF39E1A3A954F84B92C78DA45AE54B46D2FF98B4AAB1AEF331CF00009A338B9792C165C984573C69862A50042882C2CBA4EEFAC08D38B600F6BC8A896AC6CB4C14EEDA27D5F7CCE0972E6CD8F40AC9FB04E634E20808023D240E75C0579B5B97CCAE7800AC6B4FCF32E03A80FB4914A8DD509500E27D67DA39FCF569E1F6B71DD58D64E1B758819F20107CF59C458FBBE1AF3BB93700971DF1FA94245553ACA6F1D316642FA8780038D829803B7160E68E40DEFD457FCE35D841C35FEEC91E7244001DC4A252401E08EE9896F6F4B45D14001680563DD200E28549E66F0620AE696E3D69DF8A060019FD24B1B9304A7D3751DB1CCABED9D2567F707FFCB0B1617F0BB2D70236BFA8E19F986F275949E8ACC1AFDD96492F03B814D27BA351D0C00206F767D0FDAD8A0D029B330B2F37567D7FA0B83FDAF41506DE1BBDE5E0EE320494AC01D491717C56D4D5E0A4B813E7F764EE61297C4EEA3B9808FE0CB4FEE2C4686B15493E03D04541943A74457DEBFFED0D1B847B177DC15730A4238BA37E228EC1242A3C80D4250E02E3926BB15B0112C62263E34952B014744B8500A425FD64635B9E8C7B952081E6D8FB8F002EAA2817D0D256BB4AC6B990A9309B09042926052011A42545A1C921B498004832C69CD1125B16967C8A202588567767DBA70EACAC1820D05F518100C74279A33FA1E280CD277B7998838A3CFDDC349EFF8324611FC95ACFD9150380B5AD4B3F02D961B1439F84B0BD644549A518331CDD49150300A57A1B44EE17F75C56AAF1630E50E24688E0D0E6CE051FAA1017A005046654B2E9070702A000B92318EDBF60CA03E017FF716695938E066028970E8FE2C612F1CA91611E2D9AFA0CD03B63DB7E06CC2A853A44E96000824888C7ADED4807531A001686F3011E36100555BA07102832E92F98A149AECD4C7A2128723A90B039A050AEAD5E139E4E524999DB8E256C5F00DBA62C009227B7025478FC3FC2F430208B29CD0002B611F8B58499A477018366468A0A36050A764E6900107A42C205F404F0C1A9A1E939B959EF4FBA0B1AAF34676AE691566F48D508EE9DC8E9A954F7EC8D2B4ED9B0DD1BB438D29CA9F918192E31040B1DDC13514EAF9CBF24F3C0A402E0F68DB587E542DE48E014C6FE3CDFB02331474655B734D6B75DECCD3571B2AE75D127A330F839A5A3498679CE889BA4A26E44A9ABB163EBF71A4F7FC51515002D99DAD341DD06700E6183D6C7014870341111216D0E34FDBC1575BFD93CE4463A6A0E92C27B00D5F81CE003723380CF35A633BD43667DC7A28B41DE4467963C953E68E9537020880890D6079AF6D72BEA5AC7FC6472417580E6B69A1300FE2BC53954DC843F78F95B244C8E94810C8E7196BDBBA5BDF6C8A1AE4E7301DB4FCCB779FBAF415FBDC38BA32DED8B9AA8E0BB2658BE6A3878DD5B204C1211880C973B8BD6B4B4D7CD9A700034671A029A7D9BD487018BA7FDB0199C2C6FF6F7650AEEE3802E5DBB71516AD09B1C2097BC3F590EF25F498A3C24396E6E5F7C04C8AB49552BE993E72EEB08A424C6CF26B953A05CD3C43380BAEB9D6909644967EC983C8C447E2E0A73733DBB17E86A371E1FC8B26788383CAE9891BB2B9C924C1E5931C0ECEB130E005AEA6B26CB33FD989D374104ACBA6C70B6E3650CC158387D9621BC3451B546EF978C275CBCEF19E74C3C00C423FB2D3A16FB73A00D5AD2511393784EE92AC050C3C8428AF30BD43959605F9A1500D143C7B37C1B03D20EF3262E500C018854B197CC0B5B0D1C4FF52E0E08236FD1717242912BA6616103E29EDC8A977169ADB83ED30A9BCA1310DC78348C514FC464044C361938E69EE3A8E282C0C9D29379D5577AACE9C50360D2E9CD4BE500C00781A5AD27EF023C03F82CC067015E3C031417DDDEF157781AE879BF5453279F05946A16E083401F04FA20D08B07809729910578A95800F820B0B4F5E483401F047AF12EC08B07800F023D007C10E883402F9E017C16E0B3002F9E012618DDDEF157781AE879BF5453279F05946A16E083401F04961E00343E64FB495FBAAEA0803D82149F9B5CE8F8E39391426FC98215376E9D178901F842FE1C6C150A5FD9666FD142273E7300DFDFC571E4A3E75C2A0600A8479C84E470BEB182588C8F4369F74160614120C93E119D89CE59B0CE271A0074A95FC5C7DE8E313C91440674CAED10ED1E1F0416E8EAA3AA5E8A1B2C7FA450413AEFDB32E10050D0FD2085F6FCE9DEA3108DE2CD0B2384A8FA494AF686377161B2B2FEE11CADF75780B62001C16E483F09B748288714A65D3FE10068AC7D3C47049713B655D26E0F4A14C47833496D702E77FD7975AD7DDEA4E30041EDE35B8C760DA077F346DEB5778ECF1F4D7692BD75F9E2CC2D454903572E6E7B8AD0192032FD916A12AFF6EF6528C45182C32F9C729736D677FDCE9B72FCB2A236D302B87341BC0A80BBD0B980E4CC6C871B2297FB62510B412BD399670CC1994ED94B1CB955122947894E7410B545C0AA200A2F6CAADBF4F264E7B55325081CC2BEE9AE07082E72CA5EE5C8ED8374DE2B3A8AEC14706A900BBFBABA7ED3DB1375DDDDCA6DED7F405AB585C25CC7F0A326CD065C67CEB4A3A9B663C47D01D7654E3C56A8BA437447D14785C366067F00E06F876F17DFAFF3CC1F32642A05051F1683434DAA8E987B5030D794CEB8F15C75DC059AD5754F0A4004E0D5E47BEC90F32CB06BF38FA6F3C5FF29007D005E4CBE27B310E4652ACA5E0280A7FDCA05804830B2F8D21E0815070029F50E8077095750CD7AEAFA7E258513029069AA03C0FD7EF61B0ED816073D1E01C999C17454CEC936AE1A2103983200683AF5DFFB10F17E38F478F303B1FD01839E03DDD3151104EE089EFF1903BE3470D85C654241884F550201133734A53B5EA808005C9A7EABCF145C02302B89042B120194E448C0D96381E1DB159406022BD2ADED705806228B7C8D5B82244DCD4AD1209E4BFA3BE266293E196571DAB9B51DDBF60A08F7B65A9A1F699887AA9DFF02DA1924AAA87C7E38BC3696EF2E62D29352C0D0E3E316C7F639E52F81E458CC424E4AD1C0F8767529451028D144A72CA52F35D677FE60AFB250A9CC8FE6F68663C0F79752C1C930CC27866544F16F1F1335AD20FB4BC9D1C602C4A74104A3CC53519C25623E871DD23A46A70E88DB40BD81E14BE69203AA9E72DAB921E776DC77E192FFDAEB876C975525666D7BDDB330B7000503C000E4D098EE1AD3A7D6B52D5BE8C2DE4D540E5050200144809B76E5AABA8DD7F942D0441ABFAD9EC0EE67EF44615D8CF619FF550850D5E5A2D78A590CF235870A0780970A07805F76F20CE0C503C08B0780179F0578F141A017EF02BC780078F100F000F041A007800F023D00CA62066B4F66BFA780F20600A9713D56986F3F5701144044C975A67EE37A1901C040322C7432934CFA0C830240D3174285870E713323813D78E8D60360448920445D85FB732528C83D53006CBA18F7111674A97827172188824D1E00132C2B1767E4C88D4326DB581120C031BA77CC1F30ED10A2FFD69877C4CA030D800867D97B3C008A2081C3060AEF8820C4E489128D6475411044120E556EDF9BC67A9D55E92E19F023CA90B40703BB799251F90EE6785FC79F8239E701500479FDB73B5F8BA42B81C8C5BBE7891A21BACB3F73176F5785BF5F5EF7E06B05390EA5D608783ADE0E2BDE7D6FF71C0300DAE622BBA17171973C008A20579CF7B864582F879BD11FA727F6C2E07DB4D4FF9280DB65F6CD42AFB5AAAEED1D0997027815200752102529699E7F92A707A45E29FA22DC2BCFF92CA088727EBAF35DF5CCBA42C87E03021C92FD11E3CDD2E418EF4F2C3AC0E1A786E06F9A6A33E3DAA62E65DD5D70D17952EE29C9C131796A20F9D7E59F0171EE2D38AD9866B6AEA9E1B7659539966D816C4DE7B166D1CCA369EE6263D525CEB9300E0DF43E94BDC55C6AFD4EC3A3172EEED8637FBCA67D416A9AED7F7AD6B9CF9BB98678DE0812B790EE6A396E5855D7F15639EAF1FF015841FD48A44C570F0000000049454E44AE426082'), $data->getContent()); - $this->assertEquals(pack('H*', '6956424F5277304B47676F414141414E53556845556741414144414141414177434149414141445959473751414141414358424957584D41414137454141414F784147564B7734624141414470556C45515652596865315A585567555552512B5A39646358624E4E4C4C4D314E6247303341724B4A585533677167484B336F776968376336442B71682F372F33346F67736A434C364B45777A622B4B54497A6F77536853574E63734C4E61734B4372536367304E79705A437935335477395934732B73366439787252505539444C4E7A7633504F64382B636D5876504C494161584B7A4C557355767461766A44775737387449596D535A7A5645526B6946722F7167316D576730614C516F65387634634636654C546441626F6B4A36653451334C37353075586F453453647A7837475539664D623166704874515941554F6159302F72636E5A67614159546F36344149554F696A72546B504D75614E71616E7347485A424A66597372556244776953674C597675662F37557038712F566857377543354C47344C494E673045584A7762682B423539736A4E5835444A6243696F544E64714E597871524531545A6F354F6D54374B58745046614D4B55665031497A5948544A67414541674C68304B5A6D6A3063676F6B4238416A702F39486E624B7A635149654B30444D4D5357787850515158583072324A49595344713577766D7430376C6A554E6B7171614B7832314E7A3463574E6C4D6941434167446E72346E5868544C48594D685135776E7543524276324A515041366C334A6741457A744742704C4143597A416278536D696F39734B64544A5A59796756523270437049586D7045524743556A455267597844414A7358336E6433667838386E454B476F6D4E304B5068786B4F5642382B55676B4731376F704B566B71425665796571657177474256717A78797153464A614F71544E47457849765253416F65314951394C53704F7A534D7166425A6F4E47716E467030544768786257617033624A323979526549675A4551724B2B31473470735675796C78743968766F6C49304B5A33537065494242736C6F626A35624F4D53574644573450395155413269324F735558667961727033575361696F7279586436353369707A2B3237482F564A723831634B74636E773837733150452F6349694C686D3332517070372B4770706D6A354D623842586D6E61307A512B367355776131676565486646735253424C3956554D445657494C2F47564C43763133554C506866513072346B7A4D55754B3368425749493143386F622B657A51454E385558476D5661724939625A37344B6A4F786F3969373064417A676257586C4D74626C357142306D6750537461704B4F794C617A4E366B434547624F6A6E49306668304F4B57454D327179504771427366722F6350354C756E4A674935696565755348716E4F6C32396E613565663435436F587A392B6F33344E5230732F5975436F4D4F62483250676C6C6B56434F426D7854744647745073432B396D68656B3076397A4B7251676B66514835665650374F64776E55486E2B36317456372F6B496B714B3833696F3338755261376E6E506B6C496A6A78535A704E2B634C703974753148325670582F594638324A464558487548372B57734954576177677269334A73466E6944502B75677878423839626875496843415172714C71345454782F38764354764B536F7172423132415864726E5942454146356A35586E3271576A687A613267446474424C3039777642767351414159454A5365466D397862597477652B504467414138397A6F636F6631784A565A5133502B4138457749412B7133696A634141414141456C46546B5375516D4343'), $data->getThumb()); - - $result = self::$repository->getById(10); - - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCreate() - { - $data = new FileData(); - $data->setAccountId(2); - $data->setName('test.jpg'); - $data->setType('image/jpg'); - $data->setExtension('JPG'); - $data->setContent('image'); - $data->setThumb('thumb'); - $data->setSize(1000); - - $this->assertEquals(5, self::$repository->create($data)); - - $result = self::$repository->getById(5); - /** @var FileExtData $resultData */ - $resultData = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(FileExtData::class, $resultData); - $this->assertEquals($data->getName(), $resultData->getName()); - $this->assertEquals($data->getType(), $resultData->getType()); - $this->assertEquals($data->getExtension(), $resultData->getExtension()); - $this->assertEquals($data->getSize(), $resultData->getSize()); - $this->assertEquals($data->getAccountId(), $resultData->getAccountId()); - $this->assertEquals($data->getContent(), $resultData->getContent()); - $this->assertEquals($data->getThumb(), $resultData->getThumb()); - - $this->assertEquals(4, self::getRowCount('AccountFile')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $result = self::$repository->getAll(); - /** @var FileExtData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(3, $result->getNumRows()); - $this->assertCount(3, $data); - $this->assertInstanceOf(FileExtData::class, $data[0]); - $this->assertEquals(4, $data[0]->getId()); - $this->assertEquals('android.png', $data[0]->getName()); - $this->assertEquals('image/png', $data[0]->getType()); - $this->assertEquals('PNG', $data[0]->getExtension()); - $this->assertEquals('Google', $data[0]->getAccountName()); - $this->assertEquals('Google', $data[0]->getClientName()); - $this->assertEquals(4295, $data[0]->getSize()); - $this->assertEquals(1, $data[0]->getAccountId()); - $this->assertEquals(pack('H*', '89504E470D0A1A0A0000000D4948445200000080000000800806000000C33E61CB00000006624B474400FF00FF00FFA0BDA793000000097048597300000B1300000B1301009A9C180000000774494D4507DD011D0E180BE2306F78000010544944415478DAED5D6B745CD575FEBE7DEFC8961F3C0C01EC45480C2B8B0026A1D4206B2CB9C27181F208D074816D59069A16280B92A6246D42520A252D210FD2248426818418C9C63CD264C182BAE1154B1A4960CAB35E506A1E5D26501C9E768464CDDCF3F5C7BDA31796A59135F28CE66C2D594B9A19DF73F7FECEB71F67DF7388329096CCC293C1E997845174D1F2FACE374B7DBCCD1B17CF0F42DDDB1BED58F2E74B9E7DBB94C76AE5000069DA05A2CE8CA8EF94FA587FF6507D1503D71A018757D9EC334A7DBC650100B2E79F4C70B0E0336B338BFEA494C75A352DF70D1AE71AB8F9A5F51DCD1E001320AB163FB159C2CD12663A58D35D1DE9D9A538CE350F351C65C6931D1038B9CBAFBA11F200983016705F96DC9B3077CE4EC7926481B0BAF7F208760C22AD69AAEBEC2A07BD960D001AD39DBF27832F986C3A694DEBDA4F9A5352816A5BC332293CD790450AE115E5A2D7B201000050D10310FE57CC9DEAD47342A98CEBB6473E5585A0F72C3077805C78EDF2FAB6B7CA46A7283359DB9E5E2D6A0DA42E9B3E73C9CA850F6547FBCCBAB69A1991719E219C0146F38420A07400E40218009102BA01F70E2D34C1BD48177457F76CDFF6A7CB9ECE8D9AF6B5A76B403C4CEA8528179D76FE92C75E2F177D86E5060089F793DC08CBFD91EBED5905E0D6E1EFB9E7D7A7A5B6CFD85E47BAE3011C23E02002F300CD00381750086086C86133C0DE8364005E045C774FF5CCDFB574A4B7105107A2E0A5C6FA8EA7771D9FE07A11339C70533919BF2C1900009ADBEACE27A31F928E3DCF1FB5EF5F7CF6E7B907375F17BCF6EE7D75845B29E3498110413A5C4415101B5A1020825072E79404821093BF0CFC4100084A10F09E889728E668EE2E58EFFAC69A27B702C0DAAE450B11059B003D09F0338D8B332F7B004C46D09549B782564FD7773314DE01E3B7441C09A91A04094862FC1322C971F14DE21E10A3062024800ECEDD1B657139A6A183C0C141C4BF5B59DFF1BD72D3A3952B00E8EC3B0E511616FCA5026D70D47110A69348883DB139314EE327E44E80313DC43F6240848E38C7A6BB570D3CCCC4E742CDBCBB2CF5586E035ED75A77906374BA8C5F20B9801A740F1404F6D379516290D871C47048CA3CA2EBA37827841FCEDEE785473FFD8937E5015014DAAF3D9BB02F89AA0110304FC87BF12E84FC10040ADB40AC0F72D13F2F5FF2E81B1E0013286B3A177D3E10AF226C7FF4CF7A09E4DEBD07C59C80981048E07527BD2EBAAFAF4E77FDD203604F23FE478EFF10AAAAEE27834F00AAA228F183095C09E5A94E8441B683DCF9DDC6F4A67FF000182FE5B72F3A8EC0DD8E7604291156168C250146413038E46E545FF4E5D50D9BBA7D1650C8CC6FAF6D20C33B6176841162A2D2B2F0AB141C28C081B2CB2C0C7FBCB6ADE610CF00632EF4D42E03ED76331D085122588E050B498A07EE08173E9072D59F3D77C9035B3D03EC2ED8EB38611189663377A0627F3AC4F8FD2CA0815F94285B93481071553119811497103198A394142008C004BA3FDE99DA7E434BF3D98107C0483EBFB5EEE32985FF06E21080026803D9769EB20827C9D14114639A158C2439192088314711A2E8E020231C1947A7FDC3CDC3564412B352C1593AFCB59B3C007635F3DB3FB91F037C3F6270485C6461BE82C7FE843B9E66204593DD41B15E2E3C09D4CD4E8AE2A430FFAEE2794D4104B25BA19D17059C51A75C7635113DDBBFA4306400C99F62F0A608BB706D7BFA2B3E06F84091E7C46B81F06BCC2B99C290544F8098706EE4AE6BAA7FF4CA217143E6842B89F01A9261D18286643549E4EB51A4D3CEAFEF782AFFD2ADBF39E1A3A954F84B92C78DA45AE54B46D2FF98B4AAB1AEF331CF00009A338B9792C165C984573C69862A50042882C2CBA4EEFAC08D38B600F6BC8A896AC6CB4C14EEDA27D5F7CCE0972E6CD8F40AC9FB04E634E20808023D240E75C0579B5B97CCAE7800AC6B4FCF32E03A80FB4914A8DD509500E27D67DA39FCF569E1F6B71DD58D64E1B758819F20107CF59C458FBBE1AF3BB93700971DF1FA94245553ACA6F1D316642FA8780038D829803B7160E68E40DEFD457FCE35D841C35FEEC91E7244001DC4A252401E08EE9896F6F4B45D14001680563DD200E28549E66F0620AE696E3D69DF8A060019FD24B1B9304A7D3751DB1CCABED9D2567F707FFCB0B1617F0BB2D70236BFA8E19F986F275949E8ACC1AFDD96492F03B814D27BA351D0C00206F767D0FDAD8A0D029B330B2F37567D7FA0B83FDAF41506DE1BBDE5E0EE320494AC01D491717C56D4D5E0A4B813E7F764EE61297C4EEA3B9808FE0CB4FEE2C4686B15493E03D04541943A74457DEBFFED0D1B847B177DC15730A4238BA37E228EC1242A3C80D4250E02E3926BB15B0112C62263E34952B014744B8500A425FD64635B9E8C7B952081E6D8FB8F002EAA2817D0D256BB4AC6B990A9309B09042926052011A42545A1C921B498004832C69CD1125B16967C8A202588567767DBA70EACAC1820D05F518100C74279A33FA1E280CD277B7998838A3CFDDC349EFF8324611FC95ACFD9150380B5AD4B3F02D961B1439F84B0BD644549A518331CDD49150300A57A1B44EE17F75C56AAF1630E50E24688E0D0E6CE051FAA1017A005046654B2E9070702A000B92318EDBF60CA03E017FF716695938E066028970E8FE2C612F1CA91611E2D9AFA0CD03B63DB7E06CC2A853A44E96000824888C7ADED4807531A001686F3011E36100555BA07102832E92F98A149AECD4C7A2128723A90B039A050AEAD5E139E4E524999DB8E256C5F00DBA62C009227B7025478FC3FC2F430208B29CD0002B611F8B58499A477018366468A0A36050A764E6900107A42C205F404F0C1A9A1E939B959EF4FBA0B1AAF34676AE691566F48D508EE9DC8E9A954F7EC8D2B4ED9B0DD1BB438D29CA9F918192E31040B1DDC13514EAF9CBF24F3C0A402E0F68DB587E542DE48E014C6FE3CDFB02331474655B734D6B75DECCD3571B2AE75D127A330F839A5A3498679CE889BA4A26E44A9ABB163EBF71A4F7FC51515002D99DAD341DD06700E6183D6C7014870341111216D0E34FDBC1575BFD93CE4463A6A0E92C27B00D5F81CE003723380CF35A633BD43667DC7A28B41DE4467963C953E68E9537020880890D6079AF6D72BEA5AC7FC6472417580E6B69A1300FE2BC53954DC843F78F95B244C8E94810C8E7196BDBBA5BDF6C8A1AE4E7301DB4FCCB779FBAF415FBDC38BA32DED8B9AA8E0BB2658BE6A3878DD5B204C1211880C973B8BD6B4B4D7CD9A700034671A029A7D9BD487018BA7FDB0199C2C6FF6F7650AEEE3802E5DBB71516AD09B1C2097BC3F590EF25F498A3C24396E6E5F7C04C8AB49552BE993E72EEB08A424C6CF26B953A05CD3C43380BAEB9D6909644967EC983C8C447E2E0A73733DBB17E86A371E1FC8B26788383CAE9891BB2B9C924C1E5931C0ECEB130E005AEA6B26CB33FD989D374104ACBA6C70B6E3650CC158387D9621BC3451B546EF978C275CBCEF19E74C3C00C423FB2D3A16FB73A00D5AD2511393784EE92AC050C3C8428AF30BD43959605F9A1500D143C7B37C1B03D20EF3262E500C018854B197CC0B5B0D1C4FF52E0E08236FD1717242912BA6616103E29EDC8A977169ADB83ED30A9BCA1310DC78348C514FC464044C361938E69EE3A8E282C0C9D29379D5577AACE9C50360D2E9CD4BE500C00781A5AD27EF023C03F82CC067015E3C031417DDDEF157781AE879BF5453279F05946A16E083401F04FA20D08B07809729910578A95800F820B0B4F5E483401F047AF12EC08B07800F023D007C10E883402F9E017C16E0B3002F9E012618DDDEF157781AE879BF5453279F05946A16E083401F04961E00343E64FB495FBAAEA0803D82149F9B5CE8F8E39391426FC98215376E9D178901F842FE1C6C150A5FD9666FD142273E7300DFDFC571E4A3E75C2A0600A8479C84E470BEB182588C8F4369F74160614120C93E119D89CE59B0CE271A0074A95FC5C7DE8E313C91440674CAED10ED1E1F0416E8EAA3AA5E8A1B2C7FA450413AEFDB32E10050D0FD2085F6FCE9DEA3108DE2CD0B2384A8FA494AF686377161B2B2FEE11CADF75780B62001C16E483F09B748288714A65D3FE10068AC7D3C47049713B655D26E0F4A14C47833496D702E77FD7975AD7DDEA4E30041EDE35B8C760DA077F346DEB5778ECF1F4D7692BD75F9E2CC2D454903572E6E7B8AD0192032FD916A12AFF6EF6528C45182C32F9C729736D677FDCE9B72FCB2A236D302B87341BC0A80BBD0B980E4CC6C871B2297FB62510B412BD399670CC1994ED94B1CB955122947894E7410B545C0AA200A2F6CAADBF4F264E7B55325081CC2BEE9AE07082E72CA5EE5C8ED8374DE2B3A8AEC14706A900BBFBABA7ED3DB1375DDDDCA6DED7F405AB585C25CC7F0A326CD065C67CEB4A3A9B663C47D01D7654E3C56A8BA437447D14785C366067F00E06F876F17DFAFF3CC1F32642A05051F1683434DAA8E987B5030D794CEB8F15C75DC059AD5754F0A4004E0D5E47BEC90F32CB06BF38FA6F3C5FF29007D005E4CBE27B310E4652ACA5E0280A7FDCA05804830B2F8D21E0815070029F50E8077095750CD7AEAFA7E258513029069AA03C0FD7EF61B0ED816073D1E01C999C17454CEC936AE1A2103983200683AF5DFFB10F17E38F478F303B1FD01839E03DDD3151104EE089EFF1903BE3470D85C654241884F550201133734A53B5EA808005C9A7EABCF145C02302B89042B120194E448C0D96381E1DB159406022BD2ADED705806228B7C8D5B82244DCD4AD1209E4BFA3BE266293E196571DAB9B51DDBF60A08F7B65A9A1F699887AA9DFF02DA1924AAA87C7E38BC3696EF2E62D29352C0D0E3E316C7F639E52F81E458CC424E4AD1C0F8767529451028D144A72CA52F35D677FE60AFB250A9CC8FE6F68663C0F79752C1C930CC27866544F16F1F1335AD20FB4BC9D1C602C4A74104A3CC53519C25623E871DD23A46A70E88DB40BD81E14BE69203AA9E72DAB921E776DC77E192FFDAEB876C975525666D7BDDB330B7000503C000E4D098EE1AD3A7D6B52D5BE8C2DE4D540E5050200144809B76E5AABA8DD7F942D0441ABFAD9EC0EE67EF44615D8CF619FF550850D5E5A2D78A590CF235870A0780970A07805F76F20CE0C503C08B0780179F0578F141A017EF02BC780078F100F000F041A007800F023D00CA62066B4F66BFA780F20600A9713D56986F3F5701144044C975A67EE37A1901C040322C7432934CFA0C830240D3174285870E713323813D78E8D60360448920445D85FB732528C83D53006CBA18F7111674A97827172188824D1E00132C2B1767E4C88D4326DB581120C031BA77CC1F30ED10A2FFD69877C4CA030D800867D97B3C008A2081C3060AEF8820C4E489128D6475411044120E556EDF9BC67A9D55E92E19F023CA90B40703BB799251F90EE6785FC79F8239E701500479FDB73B5F8BA42B81C8C5BBE7891A21BACB3F73176F5785BF5F5EF7E06B05390EA5D608783ADE0E2BDE7D6FF71C0300DAE622BBA17171973C008A20579CF7B864582F879BD11FA727F6C2E07DB4D4FF9280DB65F6CD42AFB5AAAEED1D0997027815200752102529699E7F92A707A45E29FA22DC2BCFF92CA088727EBAF35DF5CCBA42C87E03021C92FD11E3CDD2E418EF4F2C3AC0E1A786E06F9A6A33E3DAA62E65DD5D70D17952EE29C9C131796A20F9D7E59F0171EE2D38AD9866B6AEA9E1B7659539966D816C4DE7B166D1CCA369EE6263D525CEB9300E0DF43E94BDC55C6AFD4EC3A3172EEED8637FBCA67D416A9AED7F7AD6B9CF9BB98678DE0812B790EE6A396E5855D7F15639EAF1FF015841FD48A44C570F0000000049454E44AE426082'), $data[0]->getContent()); - $this->assertEquals(pack('H*', '6956424F5277304B47676F414141414E53556845556741414144414141414177434149414141445959473751414141414358424957584D41414137454141414F784147564B7734624141414470556C45515652596865315A585567555552512B5A39646358624E4E4C4C4D314E6247303341724B4A585533677167484B336F776968376336442B71682F372F33346F67736A434C364B45777A622B4B54497A6F77536853574E63734C4E61734B4372536367304E79705A437935335477395934732B73366439787252505539444C4E7A7633504F64382B636D5876504C494161584B7A4C557355767461766A44775737387449596D535A7A5645526B6946722F7167316D576730614C516F65387634634636654C546441626F6B4A36653451334C37353075586F453453647A7837475539664D623166704874515941554F6159302F72636E5A67614159546F36344149554F696A72546B504D75614E71616E7347485A424A66597372556244776953674C597675662F37557038712F566857377543354C47344C494E673045584A7762682B423539736A4E5835444A6243696F544E64714E597871524531545A6F354F6D54374B58745046614D4B55665031497A5948544A67414541674C68304B5A6D6A3063676F6B4238416A702F39486E624B7A635149654B30444D4D5357787850515158583072324A49595344713577766D7430376C6A554E6B7171614B7832314E7A3463574E6C4D6941434167446E72346E5868544C48594D685135776E7543524276324A515041366C334A6741457A744742704C4143597A416278536D696F39734B64544A5A59796756523270437049586D7045524743556A455267597844414A7358336E6433667838386E454B476F6D4E304B5068786B4F5642382B55676B4731376F704B566B71425665796571657177474256717A78797153464A614F71544E47457849765253416F65314951394C53704F7A534D7166425A6F4E47716E467030544768786257617033624A323979526549675A4551724B2B31473470735675796C78743968766F6C49304B5A33537065494242736C6F626A35624F4D53574644573450395155413269324F735558667961727033575361696F7279586436353369707A2B3237482F564A723831634B74636E773837733150452F6349694C686D3332517070372B4770706D6A354D623842586D6E61307A512B367355776131676565486646735253424C3956554D445657494C2F47564C43763133554C506866513072346B7A4D55754B3368425749493143386F622B657A51454E385558476D5661724939625A37344B6A4F786F3969373064417A676257586C4D74626C357142306D6750537461704B4F794C617A4E366B434547624F6A6E49306668304F4B57454D327179504771427366722F6350354C756E4A674935696565755348716E4F6C32396E613565663435436F587A392B6F33344E5230732F5975436F4D4F62483250676C6C6B56434F426D7854744647745073432B396D68656B3076397A4B7251676B66514835665650374F64776E55486E2B36317456372F6B496B714B3833696F3338755261376E6E506B6C496A6A78535A704E2B634C703974753148325670582F594638324A464558487548372B57734954576177677269334A73466E6944502B75677878423839626875496843415172714C71345454782F38764354764B536F7172423132415864726E5942454146356A35586E3271576A687A613267446474424C3039777642767351414159454A5365466D397862597477652B504467414138397A6F636F6631784A565A5133502B4138457749412B7133696A634141414141456C46546B5375516D4343'), $data[0]->getThumb()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('android'); - - $result = self::$repository->search($itemSearchData); - /** @var FileExtData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(FileExtData::class, $data[0]); - $this->assertEquals('android.png', $data[0]->getName()); - $this->assertEquals('image/png', $data[0]->getType()); - $this->assertEquals('PNG', $data[0]->getExtension()); - $this->assertEquals('Google', $data[0]->getAccountName()); - $this->assertEquals('Google', $data[0]->getClientName()); - $this->assertEquals(4295, $data[0]->getSize()); - $this->assertEquals(1, $data[0]->getAccountId()); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString(''); - - $result = self::$repository->search($itemSearchData); - $this->assertEquals(3, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByAccountId() - { - $result = self::$repository->getByAccountId(1); - /** @var FileData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertInstanceOf(FileData::class, $data[0]); - $this->assertEquals(4, $data[0]->getId()); - $this->assertEquals('android.png', $data[0]->getName()); - $this->assertEquals('image/png', $data[0]->getType()); - $this->assertEquals('PNG', $data[0]->getExtension()); - $this->assertEquals(4295, $data[0]->getSize()); - $this->assertEquals(1, $data[0]->getAccountId()); - - $this->assertInstanceOf(FileData::class, $data[1]); - $this->assertEquals(1, $data[1]->getId()); - $this->assertEquals('sysPass.xml', $data[1]->getName()); - $this->assertEquals('text/xml', $data[1]->getType()); - $this->assertEquals('XML', $data[1]->getExtension()); - $this->assertEquals(1312, $data[1]->getSize()); - $this->assertEquals(1, $data[1]->getAccountId()); - $this->assertEquals(pack('H*', '3C3F786D6C2076657273696F6E3D22312E302220656E636F64696E673D225554462D38223F3E0A3C526F6F743E0A20203C4D6574613E0A202020203C47656E657261746F723E737973506173733C2F47656E657261746F723E0A202020203C56657273696F6E3E312E322E303C2F56657273696F6E3E0A202020203C54696D653E313433393332353330343C2F54696D653E0A202020203C557365722069643D2231223E61646D696E3C2F557365723E0A202020203C47726F75702069643D2231223E41646D696E733C2F47726F75703E0A202020203C486173683E36646232633238323731393136326630663136316531343731653734636531623C2F486173683E0A20203C2F4D6574613E0A20203C43617465676F726965733E0A202020203C43617465676F72792069643D2231223E0A2020202020203C6E616D653E485454503C2F6E616D653E0A2020202020203C6465736372697074696F6E2F3E0A202020203C2F43617465676F72793E0A20203C2F43617465676F726965733E0A20203C437573746F6D6572733E0A202020203C437573746F6D65722069643D2231223E0A2020202020203C6E616D653E476F6F676C6520496E632E3C2F6E616D653E0A2020202020203C6465736372697074696F6E2F3E0A202020203C2F437573746F6D65723E0A202020203C437573746F6D65722069643D2232223E0A2020202020203C6E616D653E4D6963726F736F667420496E633C2F6E616D653E0A2020202020203C6465736372697074696F6E2F3E0A202020203C2F437573746F6D65723E0A20203C2F437573746F6D6572733E0A20203C4163636F756E74733E0A202020203C4163636F756E742069643D2231223E0A2020202020203C6E616D653E476F6F676C653C2F6E616D653E0A2020202020203C637573746F6D657249643E313C2F637573746F6D657249643E0A2020202020203C63617465676F727949643E313C2F63617465676F727949643E0A2020202020203C6C6F67696E3E61646D696E3C2F6C6F67696E3E0A2020202020203C75726C3E382E382E382E383C2F75726C3E0A2020202020203C6E6F7465732F3E0A2020202020203C706173733E6C4E66513133634B6A384D592B79434F346652536B4773494334357247454C442F424E69345654614671593D3C2F706173733E0A2020202020203C7061737369763E454E6354743338503265346C643350395A553241767939664C466277386C42473947382F75414D785A6D343D3C2F7061737369763E0A202020203C2F4163636F756E743E0A202020203C4163636F756E742069643D2232223E0A2020202020203C6E616D653E4D6963726F736F66743C2F6E616D653E0A2020202020203C637573746F6D657249643E323C2F637573746F6D657249643E0A2020202020203C63617465676F727949643E313C2F63617465676F727949643E0A2020202020203C6C6F67696E3E726F6F743C2F6C6F67696E3E0A2020202020203C75726C3E342E342E342E343C2F75726C3E0A2020202020203C6E6F7465733E4E6F746173206465206D6963726F66736F66743C2F6E6F7465733E0A2020202020203C706173733E3352394F48632B53335A4E56684D795948352F784C476C76625246662F5367573348527261322B325349453D3C2F706173733E0A2020202020203C7061737369763E763637306A596B43547178635332344C4F65453077672B304330376A734C2F4635342B6E56484963544F773D3C2F7061737369763E0A202020203C2F4163636F756E743E0A20203C2F4163636F756E74733E0A3C2F526F6F743E0A'), $data[1]->getContent()); - $this->assertEquals(pack('H*', '6E6F5F7468756D62'), $data[1]->getThumb()); - - $result = self::$repository->getByAccountId(10); - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch() - { - $result = self::$repository->getByIdBatch([1, 2, 3]); - /** @var FileData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertInstanceOf(FileExtData::class, $data[0]); - $this->assertEquals(1, $data[0]->getId()); - $this->assertInstanceOf(FileExtData::class, $data[1]); - $this->assertEquals(3, $data[1]->getId()); - - $result = self::$repository->getByIdBatch([]); - $this->assertEquals(0, $result->getNumRows()); - } -} diff --git a/tests/SPT/Repositories/AccountHistoryRepositoryTest.php b/tests/SPT/Repositories/AccountHistoryRepositoryTest.php deleted file mode 100644 index f190343b..00000000 --- a/tests/SPT/Repositories/AccountHistoryRepositoryTest.php +++ /dev/null @@ -1,261 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use Defuse\Crypto\Exception\EnvironmentIsBrokenException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -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\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Infrastructure\Account\Repositories\AccountHistoryRepository; -use SP\Util\PasswordUtil; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class AccountHistoryRepositoryTest - * - * @package SPT\Repositories - */ -class AccountHistoryRepositoryTest extends DatabaseTestCase -{ - /** - * @var AccountHistoryRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(AccountHistoryRepository::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDelete() - { - $this->assertEquals(0, self::$repository->delete(1)); - $this->assertEquals(1, self::$repository->delete(3)); - $this->assertEquals(1, self::$repository->delete(4)); - - $this->assertEquals(3, self::getRowCount('AccountHistory')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $result = self::$repository->getAll(); - $data = $result->getDataAsArray(); - - $this->assertEquals(5, $result->getNumRows()); - $this->assertCount(5, $data); - $this->assertEquals(7, $data[0]->id); - $this->assertEquals('2018-06-13 20:14:23', $data[0]->dateEdit); - $this->assertEquals('2018-06-05 22:11:40', $data[0]->dateAdd); - $this->assertEquals('admin', $data[0]->userAdd); - $this->assertEquals('admin', $data[0]->userEdit); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAccountsPassData() - { - $result = self::$repository->getAccountsPassData(); - $data = $result->getDataAsArray(); - - $this->assertEquals(5, $result->getNumRows()); - $this->assertCount(5, $data); - $this->assertEquals(3, $data[0]->id); - $this->assertEquals('Google', $data[0]->name); - $this->assertEquals(pack('H*', '646566353032303064396362643366376662646536326637663732663861383732623430613839386131643134333933663662623033316664343362366461643762626564643634386437363964346634616234386638336636653236396166623734636261383134313363626162326461393733343934613231653934666331616664633637313732316562356666396562646132613665313937626233333563613632383830393934333863643731333230383132316430366433303838'), $data[0]->pass); - $this->assertEquals(pack('H*', '6465663130303030646566353032303032636635623034396437656539356531653838663166613438643061616132663133613163663766346238316165663837326134373665316461653661353865316666626438346130383166303062633138646136373265653935643234626564336565303063333262646262303433336633356534323263616337613238363532336233313666316137333462616337343839346631333632643863376430373861373862396135633064396239653061353537626562666336636566623766363166376330393734356461623536373762303436313865343936383434663932666364303634316330303935636239363938336361336631363161623134663339643536636233653938333833613062396464356365383736333334376364363933313563306436343362623937366139383831376632346431303364316533353133306262393862353034353262346334663934663162323531383632356530653331346438343430323362666334306264616265376437386238663632326535353338636537663431626261616461613138646333333662623762636565333030656565333734616537356365303131363731323239383132383964346634383661376635303136303835336138663335653366393230383632386162373332343335633037656432616234'), $data[0]->key); - $this->assertEquals(pack('H*', '24327924313024787473754E325055766753482F306D7266426C73624F4163745667436A596371447143364C3354395172614E785A43345258475961'), $data[0]->mPassHash); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetHistoryForAccount() - { - $result = self::$repository->getHistoryForAccount(2); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertEquals(3, $data[0]->id); - $this->assertEquals('2018-06-06 22:20:29', $data[0]->dateEdit); - $this->assertEquals('2018-06-05 22:49:34', $data[0]->dateAdd); - $this->assertEquals('admin', $data[0]->userAdd); - $this->assertEquals('admin', $data[0]->userEdit); - - $result = self::$repository->getHistoryForAccount(1); - $this->assertEquals(4, $result->getNumRows()); - - $result = self::$repository->getHistoryForAccount(10); - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws EnvironmentIsBrokenException - * @throws ConstraintException - * @throws QueryException - */ - public function testCreate() - { - $result = self::$repository->create(new AccountHistoryCreateDto(2, true, false, PasswordUtil::generateRandomBytes())); - $this->assertEquals(8, $result); - - $result = self::$repository->create(new AccountHistoryCreateDto(2, true, true, PasswordUtil::generateRandomBytes())); - $this->assertEquals(9, $result); - - $result = self::$repository->create(new AccountHistoryCreateDto(10, true, false, PasswordUtil::generateRandomBytes())); - $this->assertEquals(0, $result); - - $this->assertEquals(7, self::getRowCount('AccountHistory')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Google'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(5, $result->getNumRows()); - $this->assertCount(5, $data); - $this->assertEquals(7, $data[0]->id); - - $itemSearchData->setSeachString('test'); - $result = self::$repository->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(3, self::$repository->deleteByIdBatch([1, 3, 4, 5])); - $this->assertEquals(0, self::$repository->deleteByIdBatch([])); - - $this->assertEquals(2, self::getRowCount('AccountHistory')); - } - - /** - * @throws SPException - */ - public function testGetById() - { - $result = self::$repository->getById(3); - /** @var AccountHistory $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $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()); - $this->assertEquals(1, $data->getUserId()); - $this->assertEquals(1, $data->getUserEditId()); - - $result = self::$repository->getById(1); - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws EnvironmentIsBrokenException - * @throws SPException - */ - public function testUpdatePassword() - { - $request = new AccountPasswordRequest(); - $request->id = 3; - $request->pass = PasswordUtil::generateRandomBytes(); - $request->key = PasswordUtil::generateRandomBytes(); - $request->hash = PasswordUtil::generateRandomBytes(); - - $this->assertEquals(1, self::$repository->updatePassword($request)); - - $result = self::$repository->getById(3); - /** @var AccountHistory $data */ - $data = $result->getData(); - - $this->assertEquals($request->pass, $data->getPass()); - $this->assertEquals($request->key, $data->getKey()); - - $request->id = 10; - $this->assertEquals(0, self::$repository->updatePassword($request)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByAccountIdBatch() - { - $this->assertEquals(4, self::$repository->deleteByAccountIdBatch([1, 3])); - - $this->assertEquals(0, self::$repository->deleteByAccountIdBatch([10])); - - $this->assertEquals(0, self::$repository->deleteByAccountIdBatch([])); - - $this->assertEquals(1, self::getRowCount('AccountHistory')); - } -} diff --git a/tests/SPT/Repositories/AccountToFavoriteRepositoryTest.php b/tests/SPT/Repositories/AccountToFavoriteRepositoryTest.php deleted file mode 100644 index 6f3c3fba..00000000 --- a/tests/SPT/Repositories/AccountToFavoriteRepositoryTest.php +++ /dev/null @@ -1,110 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Domain\Account\Ports\AccountToFavoriteRepositoryInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Infrastructure\Account\Repositories\AccountToFavoriteRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class AccountFavoriteRepositoryTest - * - * @package SPT\Repositories - */ -class AccountToFavoriteRepositoryTest extends DatabaseTestCase -{ - /** - * @var AccountToFavoriteRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(AccountToFavoriteRepository::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testAdd() - { - $this->assertEquals(0, self::$repository->add(1, 2)); - - $this->expectException(ConstraintException::class); - - self::$repository->add(3, 1); - - self::$repository->add(1, 3); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetForUserId() - { - $result = self::$repository->getForUserId(3); - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertArrayHasKey(1, $data); - $this->assertArrayHasKey(2, $data); - $this->assertEquals(3, $data[1]); - $this->assertEquals(3, $data[2]); - - $result = self::$repository->getForUserId(10); - - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDelete() - { - $this->assertEquals(1, self::$repository->delete(1, 3)); - $this->assertEquals(0, self::$repository->delete(10, 1)); - } -} diff --git a/tests/SPT/Repositories/AccountToTagRepositoryTest.php b/tests/SPT/Repositories/AccountToTagRepositoryTest.php deleted file mode 100644 index 3eb62d65..00000000 --- a/tests/SPT/Repositories/AccountToTagRepositoryTest.php +++ /dev/null @@ -1,151 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemData; -use SP\Domain\Account\Dtos\AccountRequest; -use SP\Domain\Account\Ports\AccountToTagRepositoryInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Infrastructure\Account\Repositories\AccountToTagRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class AccountToTagRepositoryTest - * - * Tests de integración para la comprobación de operaciones de etiquetas asociadas a cuentas - * - * @package SPT - */ -class AccountToTagRepositoryTest extends DatabaseTestCase -{ - /** - * @var AccountToTagRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(AccountToTagRepository::class); - } - - /** - * Comprobar la obtención de etiquetas por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetTagsByAccountId() - { - $this->assertEquals(2, self::$repository->getTagsByAccountId(1)->getNumRows()); - $this->assertEquals(0, self::$repository->getTagsByAccountId(10)->getNumRows()); - } - - /** - * Comprobar la creación de etiquetas asociadas a las cuentas - * - * @throws ConstraintException - * @throws QueryException - */ - public function testAdd() - { - $accountRequest = new AccountRequest(); - $accountRequest->id = 1; - $accountRequest->tags = [3]; - - $this->assertEquals(1, self::$repository->add($accountRequest)); - - $result = self::$repository->getTagsByAccountId($accountRequest->id); - $data = $result->getDataAsArray(); - - $this->assertCount(3, $data); - $this->assertInstanceOf(ItemData::class, $data[0]); - $this->assertInstanceOf(ItemData::class, $data[1]); - $this->assertInstanceOf(ItemData::class, $data[2]); - - $this->expectException(ConstraintException::class); - - $accountRequest->tags = [1]; - - self::$repository->add($accountRequest); - - $accountRequest->id = 10; - - self::$repository->add($accountRequest); - } - - - /** - * Comprobar la eliminación de etiquetas por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByAccountId() - { - $this->assertEquals(2, self::$repository->deleteByAccountId(1)); - - $this->assertEquals(0, self::$repository->getTagsByAccountId(1)->getNumRows()); - - $this->assertEquals(0, self::$repository->deleteByAccountId(10)); - } - - /** - * Comprobar la actualización de etiquetas por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdate() - { - $accountRequest = new AccountRequest(); - $accountRequest->id = 1; - $accountRequest->tags = [1, 2]; - - self::$repository->update($accountRequest); - - $result = self::$repository->getTagsByAccountId($accountRequest->id); - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertInstanceOf(ItemData::class, $data[0]); - $this->assertInstanceOf(ItemData::class, $data[1]); - } -} diff --git a/tests/SPT/Repositories/AccountToUserGroupRepositoryTest.php b/tests/SPT/Repositories/AccountToUserGroupRepositoryTest.php deleted file mode 100644 index c7a56ee2..00000000 --- a/tests/SPT/Repositories/AccountToUserGroupRepositoryTest.php +++ /dev/null @@ -1,344 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemData; -use SP\Domain\Account\Dtos\AccountRequest; -use SP\Domain\Account\Ports\AccountToUserGroupRepositoryInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Infrastructure\Account\Repositories\AccountToUserGroupRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class AccountToUserGroupRepositoryTest - * - * Tests de integración para la comprobación de operaciones de grupos de usuarios asociados a cuentas - * - * @package SPT - */ -class AccountToUserGroupRepositoryTest extends DatabaseTestCase -{ - /** - * @var AccountToUserGroupRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(AccountToUserGroupRepository::class); - } - - /** - * Comprobar la obtención de grupos de usuarios por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUserGroupsByAccountId() - { - $result = self::$repository->getUserGroupsByAccountId(1); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(ItemData::class, $data[0]); - - $userGroupsView = array_filter($data, function ($user) { - return (int)$user->isEdit === 0; - }); - - $this->assertCount(0, $userGroupsView); - - $userGroupsEdit = array_filter($data, function ($user) { - return (int)$user->isEdit === 1; - }); - - $this->assertCount(1, $userGroupsEdit); - - $result = self::$repository->getUserGroupsByAccountId(2); - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertInstanceOf(ItemData::class, $data[0]); - - $userGroupsView = array_filter($data, function ($user) { - return (int)$user->isEdit === 0; - }); - - $this->assertCount(2, $userGroupsView); - - $userGroupsEdit = array_filter($data, function ($user) { - return (int)$user->isEdit === 1; - }); - - $this->assertCount(0, $userGroupsEdit); - - $this->assertEquals(0, self::$repository->getUserGroupsByAccountId(3)->getNumRows()); - } - - /** - * Comprobar la actualización de grupos de usuarios por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdate() - { - $accountRequest = new AccountRequest(); - $accountRequest->id = 1; - $accountRequest->userGroupsView = [1, 2, 3]; - - self::$repository->updateByType($accountRequest, false); - - $result = self::$repository->getUserGroupsByAccountId($accountRequest->id); - $data = $result->getDataAsArray(); - - $this->assertEquals(3, $result->getNumRows()); - $this->assertInstanceOf(ItemData::class, $data[0]); - $this->assertEquals(0, (int)$data[0]->isEdit); - $this->assertInstanceOf(ItemData::class, $data[1]); - $this->assertEquals(0, (int)$data[1]->isEdit); - $this->assertInstanceOf(ItemData::class, $data[2]); - $this->assertEquals(0, (int)$data[2]->isEdit); - - $this->expectException(ConstraintException::class); - - $accountRequest->userGroupsView = [10]; - - self::$repository->updateByType($accountRequest, false); - - $accountRequest->id = 3; - $accountRequest->userGroupsView = [1, 2, 3]; - - self::$repository->updateByType($accountRequest, false); - } - - /** - * Comprobar la actualización de grupos de usuarios con permisos de modificación por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdateEdit() - { - $accountRequest = new AccountRequest(); - $accountRequest->id = 2; - $accountRequest->userGroupsEdit = [2, 3]; - - self::$repository->updateByType($accountRequest, true); - - $result = self::$repository->getUserGroupsByAccountId($accountRequest->id); - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertInstanceOf(ItemData::class, $data[0]); - $this->assertEquals(1, (int)$data[0]->isEdit); - $this->assertInstanceOf(ItemData::class, $data[1]); - $this->assertEquals(1, (int)$data[1]->isEdit); - - $this->expectException(ConstraintException::class); - - // Comprobar que se lanza excepción al añadir usuarios no existentes - $accountRequest->userGroupsEdit = [10]; - - self::$repository->updateByType($accountRequest, true); - - // Comprobar que se lanza excepción al añadir usuarios a cuenta no existente - $accountRequest->id = 3; - $accountRequest->userGroupsEdit = [2, 3]; - - self::$repository->updateByType($accountRequest, true); - } - - /** - * Comprobar la eliminación de grupos de usuarios por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testViewDeleteByAccountId() - { - $this->assertEquals(2, self::$repository->deleteTypeByAccountId(2, false)); - - $this->assertEquals(0, self::$repository->getUserGroupsByAccountId(2)->getNumRows()); - - $this->assertEquals(0, self::$repository->deleteTypeByAccountId(10, false)); - - $this->assertEquals(1, self::getRowCount('AccountToUserGroup')); - } - - /** - * Comprobar la eliminación de grupos de usuarios por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByAccountId() - { - $this->assertEquals(1, self::$repository->deleteByAccountId(1)); - - $this->assertEquals(0, self::$repository->getUserGroupsByAccountId(1)->getNumRows()); - - $this->assertEquals(0, self::$repository->deleteByAccountId(10)); - - $this->assertEquals(2, self::getRowCount('AccountToUserGroup')); - } - - /** - * Comprobar la insercción de grupos de usuarios con permisos de modificación por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testAddEdit() - { - $accountRequest = new AccountRequest(); - $accountRequest->id = 2; - $accountRequest->userGroupsEdit = [1, 2, 3]; - - self::$repository->addByType($accountRequest, true); - - $result = self::$repository->getUserGroupsByAccountId($accountRequest->id); - $data = $result->getDataAsArray(); - - $this->assertEquals(3, $result->getNumRows()); - $this->assertInstanceOf(ItemData::class, $data[0]); - $this->assertInstanceOf(ItemData::class, $data[1]); - $this->assertInstanceOf(ItemData::class, $data[2]); - - $this->expectException(ConstraintException::class); - - // Comprobar que se lanza excepción al añadir usuarios no existentes - $accountRequest->userGroupsEdit = [10]; - - self::$repository->addByType($accountRequest, true); - - // Comprobar que se lanza excepción al añadir grupos de usuarios a cuenta no existente - $accountRequest->id = 3; - $accountRequest->userGroupsEdit = [1, 2, 3]; - - self::$repository->addByType($accountRequest, true); - } - - /** - * Comprobar la insercción de grupos de usuarios por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testAdd() - { - $accountRequest = new AccountRequest(); - $accountRequest->id = 2; - $accountRequest->userGroupsView = [1, 2, 3]; - - $this->assertEquals(3, self::$repository->addByType($accountRequest, false)); - - $result = self::$repository->getUserGroupsByAccountId($accountRequest->id); - - $this->assertEquals(3, $result->getNumRows()); - - $data = $result->getDataAsArray(); - - $this->assertCount(3, $data); - $this->assertInstanceOf(ItemData::class, $data[0]); - $this->assertInstanceOf(ItemData::class, $data[1]); - $this->assertInstanceOf(ItemData::class, $data[2]); - - $this->expectException(ConstraintException::class); - - // Comprobar que se lanza excepción al añadir usuarios no existentes - $accountRequest->userGroupsView = [10]; - - self::$repository->addByType($accountRequest, false); - - // Comprobar que se lanza excepción al añadir grupos de usuarios a cuenta no existente - $accountRequest->id = 3; - $accountRequest->userGroupsView = [1, 2, 3]; - - self::$repository->addByType($accountRequest, false); - } - - /** - * Comprobar la eliminación de grupos de usuarios con permisos de modificación por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteEditByAccountId() - { - $this->assertEquals(1, self::$repository->deleteTypeByAccountId(1, true)); - $this->assertEquals(0, self::$repository->getUserGroupsByAccountId(1)->getNumRows()); - - $this->assertEquals(0, self::$repository->deleteTypeByAccountId(10, true)); - - $this->assertEquals(2, self::getRowCount('AccountToUserGroup')); - } - - /** - * Comprobar la obtención de grupos de usuarios por Id de grupo - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUserGroupsByUserGroupId() - { - $this->assertEquals(2, self::$repository->getUserGroupsByUserGroupId(2)->getNumRows()); - - $this->assertEquals(1, self::$repository->getUserGroupsByUserGroupId(3)->getNumRows()); - - $this->assertEquals(0, self::$repository->getUserGroupsByUserGroupId(10)->getNumRows()); - } - - /** - * Comprobar la eliminación de grupos de usuarios por Id de grupo - * - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByUserGroupId() - { - $this->assertEquals(2, self::$repository->deleteByUserGroupId(2)); - - $this->assertEquals(0, self::$repository->deleteByUserGroupId(1)); - - $this->assertEquals(0, self::$repository->deleteByUserGroupId(10)); - } -} diff --git a/tests/SPT/Repositories/AccountToUserRepositoryTest.php b/tests/SPT/Repositories/AccountToUserRepositoryTest.php deleted file mode 100644 index 235b0458..00000000 --- a/tests/SPT/Repositories/AccountToUserRepositoryTest.php +++ /dev/null @@ -1,321 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemData; -use SP\Domain\Account\Dtos\AccountRequest; -use SP\Domain\Account\Ports\AccountToUserRepositoryInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Infrastructure\Account\Repositories\AccountToUserRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class AccountToUserRepositoryTest - * - * Tests de integración para la comprobación de operaciones de usuarios asociados a cuentas - * - * @package SPT - */ -class AccountToUserRepositoryTest extends DatabaseTestCase -{ - /** - * @var AccountToUserRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(AccountToUserRepository::class); - } - - /** - * Comprobar la obtención de usuarios por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUsersByAccountId() - { - $result = self::$repository->getUsersByAccountId(1); - $this->assertEquals(1, $result->getNumRows()); - - $resultData = $result->getDataAsArray(); - - $this->assertCount(1, $resultData); - $this->assertInstanceOf(ItemData::class, $resultData[0]); - - $usersView = array_filter($resultData, function ($user) { - return (int)$user->isEdit === 0; - }); - - $this->assertCount(0, $usersView); - - $usersEdit = array_filter($resultData, function ($user) { - return (int)$user->isEdit === 1; - }); - - $this->assertCount(1, $usersEdit); - - $result = self::$repository->getUsersByAccountId(2); - $this->assertEquals(1, $result->getNumRows()); - - $resultData = $result->getDataAsArray(); - - $this->assertCount(1, $resultData); - $this->assertInstanceOf(ItemData::class, $resultData[0]); - - $usersView = array_filter($resultData, function ($user) { - return (int)$user->isEdit === 0; - }); - - $this->assertCount(1, $usersView); - - $usersEdit = array_filter($resultData, function ($user) { - return (int)$user->isEdit === 1; - }); - - $this->assertCount(0, $usersEdit); - - $this->assertEquals(0, self::$repository->getUsersByAccountId(3)->getNumRows()); - } - - /** - * Comprobar la actualización de usuarios por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdate() - { - $accountRequest = new AccountRequest(); - $accountRequest->id = 1; - $accountRequest->usersView = [1, 2, 3]; - - self::$repository->updateByType($accountRequest, false); - - $result = self::$repository->getUsersByAccountId($accountRequest->id); - $this->assertEquals(3, $result->getNumRows()); - - $resultData = $result->getDataAsArray(); - - $this->assertCount(3, $resultData); - $this->assertInstanceOf(ItemData::class, $resultData[0]); - $this->assertEquals(0, (int)$resultData[0]->isEdit); - $this->assertInstanceOf(ItemData::class, $resultData[1]); - $this->assertEquals(0, (int)$resultData[1]->isEdit); - $this->assertInstanceOf(ItemData::class, $resultData[2]); - $this->assertEquals(0, (int)$resultData[2]->isEdit); - - $this->expectException(ConstraintException::class); - - $accountRequest->usersView = [10]; - - self::$repository->updateByType($accountRequest, false); - - $accountRequest->id = 3; - $accountRequest->usersView = [1, 2, 3]; - - self::$repository->updateByType($accountRequest, false); - } - - /** - * Comprobar la actualización de usuarios con permisos de modificación por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdateEdit() - { - $accountRequest = new AccountRequest(); - $accountRequest->id = 2; - $accountRequest->usersEdit = [2, 3]; - - self::$repository->updateByType($accountRequest, true); - - $result = self::$repository->getUsersByAccountId($accountRequest->id); - $this->assertEquals(2, $result->getNumRows()); - - $resultData = $result->getDataAsArray(); - - $this->assertCount(2, $resultData); - $this->assertInstanceOf(ItemData::class, $resultData[0]); - $this->assertEquals(1, (int)$resultData[0]->isEdit); - $this->assertInstanceOf(ItemData::class, $resultData[1]); - $this->assertEquals(1, (int)$resultData[1]->isEdit); - - $this->expectException(ConstraintException::class); - - // Comprobar que se lanza excepción al añadir usuarios no existentes - $accountRequest->usersEdit = [10]; - - self::$repository->updateByType($accountRequest, true); - - // Comprobar que se lanza excepción al añadir usuarios a cuenta no existente - $accountRequest->id = 3; - $accountRequest->usersEdit = [2, 3]; - - self::$repository->updateByType($accountRequest, true); - } - - /** - * Comprobar la eliminación de usuarios por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteViewByAccountId() - { - $this->assertEquals(1, self::$repository->deleteTypeByAccountId(2, false)); - $this->assertEquals(0, self::$repository->getUsersByAccountId(2)->getNumRows()); - - $this->assertEquals(0, self::$repository->deleteTypeByAccountId(10, false)); - - $this->assertEquals(1, self::getRowCount('AccountToUser')); - } - - /** - * Comprobar la eliminación de usuarios por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByAccountId() - { - $this->assertEquals(1, self::$repository->deleteByAccountId(1)); - $this->assertEquals(0, self::$repository->getUsersByAccountId(1)->getNumRows()); - - $this->assertEquals(0, self::$repository->deleteByAccountId(10)); - - $this->assertEquals(1, self::getRowCount('AccountToUser')); - } - - /** - * Comprobar la insercción de usuarios con permisos de modificación por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testAddEdit() - { - $accountRequest = new AccountRequest(); - $accountRequest->id = 2; - $accountRequest->usersEdit = [1, 2, 3]; - - self::$repository->addByType($accountRequest, true); - - $result = self::$repository->getUsersByAccountId($accountRequest->id); - $this->assertEquals(3, $result->getNumRows()); - - $resultData = $result->getDataAsArray(); - - $this->assertCount(3, $resultData); - $this->assertInstanceOf(ItemData::class, $resultData[0]); - $this->assertInstanceOf(ItemData::class, $resultData[1]); - $this->assertInstanceOf(ItemData::class, $resultData[2]); - - $this->expectException(ConstraintException::class); - - // Comprobar que se lanza excepción al añadir usuarios no existentes - $accountRequest->usersEdit = [10]; - - self::$repository->addByType($accountRequest, true); - - // Comprobar que se lanza excepción al añadir usuarios a cuenta no existente - $accountRequest->id = 3; - $accountRequest->usersEdit = [1, 2, 3]; - - self::$repository->addByType($accountRequest, true); - } - - /** - * Comprobar la insercción de usuarios por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testAdd() - { - $accountRequest = new AccountRequest(); - $accountRequest->id = 2; - $accountRequest->usersView = [1, 2, 3]; - - self::$repository->addByType($accountRequest, false); - - $result = self::$repository->getUsersByAccountId($accountRequest->id); - $this->assertEquals(3, $result->getNumRows()); - - $resultData = $result->getDataAsArray(); - - $this->assertCount(3, $resultData); - $this->assertInstanceOf(ItemData::class, $resultData[0]); - $this->assertInstanceOf(ItemData::class, $resultData[1]); - $this->assertInstanceOf(ItemData::class, $resultData[2]); - - $this->expectException(ConstraintException::class); - - // Comprobar que se lanza excepción al añadir usuarios no existentes - $accountRequest->usersView = [10]; - - self::$repository->addByType($accountRequest, false); - - // Comprobar que se lanza excepción al añadir usuarios a cuenta no existente - $accountRequest->id = 3; - $accountRequest->usersView = [1, 2, 3]; - - self::$repository->addByType($accountRequest, false); - } - - /** - * Comprobar la eliminación de usuarios con permisos de modificación por Id de cuenta - * - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteEditByAccountId() - { - $this->assertEquals(1, self::$repository->deleteTypeByAccountId(1, true)); - $this->assertEquals(0, self::$repository->getUsersByAccountId(1)->getNumRows()); - - $this->assertEquals(0, self::$repository->deleteTypeByAccountId(10, true)); - - $this->assertEquals(1, self::getRowCount('AccountToUser')); - } -} diff --git a/tests/SPT/Repositories/AuthTokenRepositoryTest.php b/tests/SPT/Repositories/AuthTokenRepositoryTest.php deleted file mode 100644 index 2fb3b4bc..00000000 --- a/tests/SPT/Repositories/AuthTokenRepositoryTest.php +++ /dev/null @@ -1,349 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use Defuse\Crypto\Exception\CryptoException; -use Defuse\Crypto\Exception\EnvironmentIsBrokenException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Core\Crypt\Hash; -use SP\Core\Crypt\Vault; -use SP\DataModel\AuthToken; -use SP\DataModel\ItemSearchData; -use SP\Domain\Auth\Ports\AuthTokenRepositoryInterface; -use SP\Domain\Core\Acl\AclActionsInterface; -use SP\Domain\Core\Crypt\VaultInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Infrastructure\Auth\Repositories\AuthTokenRepository; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Util\PasswordUtil; -use SP\Util\Util; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class AuthTokenRepositoryTest - * - * @package SPT\Repositories - */ -class AuthTokenRepositoryTest extends DatabaseTestCase -{ - public const AUTH_TOKEN = '2cee8b224f48e01ef48ac172e879cc7825800a9d7ce3b23783212f4758f1c146'; - public const AUTH_TOKEN_PASS = 123456; - - /** - * @var AuthTokenRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(AuthTokenRepository::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $result = self::$repository->getById(1); - $this->assertEquals(1, $result->getNumRows()); - - $data = $result->getData(); - - $this->assertInstanceOf(AuthToken::class, $data); - $this->assertEquals(1, $data->getId()); - $this->assertEquals(AclActionsInterface::ACCOUNT_SEARCH, $data->getActionId()); - $this->assertEquals('12b9027d24efff7bfbaca8bd774a4c34b45de35e033d2b192a88f4dfaee5c233', $data->getToken()); - $this->assertNull($data->getHash()); - - $result = self::$repository->getById(2); - $this->assertEquals(1, $result->getNumRows()); - - $data = $result->getData(); - - $this->assertInstanceOf(AuthToken::class, $data); - $this->assertEquals(2, $data->getId()); - $this->assertEquals(AclActionsInterface::ACCOUNT_VIEW_PASS, $data->getActionId()); - $this->assertEquals(self::AUTH_TOKEN, $data->getToken()); - $this->assertTrue(Hash::checkHashKey(self::AUTH_TOKEN_PASS, $data->getHash())); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetTokenByUserId() - { - $this->assertEquals(self::AUTH_TOKEN, self::$repository->getTokenByUserId(1)); - - $this->assertNull(self::$repository->getTokenByUserId(3)); - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - */ - public function testGetTokenByToken() - { - $result = self::$repository->getTokenByToken(AclActionsInterface::ACCOUNT_VIEW_PASS, self::AUTH_TOKEN); - /** @var AuthToken $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertEquals(2, $data->getId()); - $this->assertEquals(AclActionsInterface::ACCOUNT_VIEW_PASS, $data->getActionId()); - $this->assertTrue(Hash::checkHashKey(self::AUTH_TOKEN_PASS, $data->getHash())); - $this->assertNotEmpty($data->getVault()); - - /** @var VaultInterface $vault */ - $vault = Util::unserialize(Vault::class, $data->getVault()); - $this->assertEquals('12345678900', $vault->getData(self::AUTH_TOKEN_PASS . self::AUTH_TOKEN)); - - $this->expectException(CryptoException::class); - - $vault->getData(1234); - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - */ - public function testRefreshVaultByUserId() - { - $vault = Vault::getInstance() - ->saveData('prueba', self::AUTH_TOKEN_PASS) - ->getSerialized(); - $hash = Hash::hashKey(self::AUTH_TOKEN_PASS); - - $this->assertEquals(1, self::$repository->refreshVaultByUserId(1, $vault, $hash)); - - $result = self::$repository->getTokenByToken(AclActionsInterface::ACCOUNT_VIEW_PASS, self::AUTH_TOKEN); - /** @var AuthToken $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - - $this->assertInstanceOf(AuthToken::class, $data); - $this->assertTrue(Hash::checkHashKey(self::AUTH_TOKEN_PASS, $data->getHash())); - $this->assertEquals($vault, $data->getVault()); - - /** @var VaultInterface $vault */ - $vault = Util::unserialize(Vault::class, $data->getVault()); - $this->assertEquals('prueba', $vault->getData(self::AUTH_TOKEN_PASS)); - } - - /** - * @throws EnvironmentIsBrokenException - * @throws ConstraintException - * @throws QueryException - */ - public function testRefreshTokenByUserId() - { - $token = PasswordUtil::generateRandomBytes(); - - // Comprobar actualización con usuario que existe - $this->assertEquals(4, self::$repository->refreshTokenByUserId(1, $token)); - $this->assertEquals($token, self::$repository->getTokenByUserId(1)); - - // Comprobar actualización con usuario que NO existe - $this->assertEquals(0, self::$repository->refreshTokenByUserId(10, $token)); - $this->assertNull(self::$repository->getTokenByUserId(10)); - } - - /** - * @throws EnvironmentIsBrokenException - * @throws ConstraintException - * @throws QueryException - * @throws DuplicatedItemException - * @throws CryptoException - */ - public function testUpdate() - { - $token = PasswordUtil::generateRandomBytes(); - $hash = Hash::hashKey('prueba123'); - $vault = Vault::getInstance()->saveData('prueba', 'prueba123'); - - $authTokenData = new AuthToken(); - $authTokenData->setId(1); - $authTokenData->setActionId(AclActionsInterface::ACCOUNT_CREATE); - $authTokenData->setCreatedBy(1); - $authTokenData->setHash($hash); - $authTokenData->setToken($token); - $authTokenData->setVault($vault); - $authTokenData->setUserId(2); - - $this->assertEquals(1, self::$repository->update($authTokenData)); - - $result = self::$repository->getTokenByToken(AclActionsInterface::ACCOUNT_CREATE, $token); - /** @var AuthToken $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(AuthToken::class, $data); - $this->assertEquals(AclActionsInterface::ACCOUNT_CREATE, $data->getActionId()); - $this->assertEquals($hash, $data->getHash()); - $this->assertEquals(2, $data->getUserId()); - $this->assertEquals($vault->getSerialized(), $data->getVault()); - - $this->expectException(DuplicatedItemException::class); - - $authTokenData->setId(2); - $authTokenData->setUserId(1); - - self::$repository->update($authTokenData); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('admin'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(4, $result->getNumRows()); - $this->assertCount(4, $data); - - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(AclActionsInterface::ACCOUNT_SEARCH, $data[0]->actionId); - $this->assertEquals(self::AUTH_TOKEN, $data[0]->token); - - $this->assertInstanceOf(stdClass::class, $data[1]); - $this->assertEquals(AclActionsInterface::ACCOUNT_VIEW, $data[1]->actionId); - $this->assertEquals(self::AUTH_TOKEN, $data[1]->token); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setSeachString('test'); - - $result = self::$repository->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $result->getDataAsArray()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(5, self::getRowCount('AuthToken')); - - $this->assertEquals(3, self::$repository->deleteByIdBatch([1, 2, 3])); - - $this->assertEquals(2, self::getRowCount('AuthToken')); - - $this->assertEquals(0, self::$repository->deleteByIdBatch([])); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUserIdForToken() - { - $this->assertEquals(1, self::$repository->getUserIdForToken(self::AUTH_TOKEN)); - - $this->assertFalse(self::$repository->getUserIdForToken('no_token')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDelete() - { - $this->assertEquals(1, self::$repository->delete(1)); - - $this->assertEquals(0, self::$repository->delete(10)); - } - - /** - * @throws CryptoException - * @throws EnvironmentIsBrokenException - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testCreate() - { - $token = PasswordUtil::generateRandomBytes(); - $hash = Hash::hashKey('prueba123'); - $vault = Vault::getInstance()->saveData('prueba', 'prueba123'); - - $authTokenData = new AuthToken(); - $authTokenData->setActionId(AclActionsInterface::ACCOUNT_CREATE); - $authTokenData->setCreatedBy(1); - $authTokenData->setHash($hash); - $authTokenData->setToken($token); - $authTokenData->setVault($vault); - $authTokenData->setUserId(2); - - $this->assertEquals(6, self::$repository->create($authTokenData)); - $this->assertEquals(6, self::getRowCount('AuthToken')); - - $result = self::$repository->getTokenByToken(AclActionsInterface::ACCOUNT_CREATE, $token); - /** @var AuthToken $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(AuthToken::class, $data); - $this->assertEquals(AclActionsInterface::ACCOUNT_CREATE, $data->getActionId()); - $this->assertEquals($hash, $data->getHash()); - $this->assertEquals(6, $data->getId()); - $this->assertEquals(2, $data->getUserId()); - $this->assertEquals($vault->getSerialized(), $data->getVault()); - - $this->expectException(DuplicatedItemException::class); - - $authTokenData->setUserId(1); - - self::$repository->create($authTokenData); - } -} diff --git a/tests/SPT/Repositories/CategoryRepositoryTest.php b/tests/SPT/Repositories/CategoryRepositoryTest.php deleted file mode 100644 index 0ace0763..00000000 --- a/tests/SPT/Repositories/CategoryRepositoryTest.php +++ /dev/null @@ -1,300 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\CategoryData; -use SP\DataModel\ItemSearchData; -use SP\Domain\Category\Ports\CategoryRepositoryInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Infrastructure\Category\Repositories\CategoryRepository; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class CategoryRepositoryTest - * - * Tests de integración para comprobar las consultas a la BBDD relativas a las categorías - * - * @package SPT - */ -class CategoryRepositoryTest extends DatabaseTestCase -{ - /** - * @var CategoryRepositoryInterface - */ - private static $repository; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(CategoryRepository::class); - } - - /** - * Comprobar los resultados de obtener las categorías por nombre - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByName() - { - $this->assertEquals(0, self::$repository->getByName('Prueba')->getNumRows()); - - $result = self::$repository->getByName('Web'); - $data = $result->getData(); - - $this->assertEquals(1, $data->getId()); - $this->assertEquals('Web sites', $data->getDescription()); - - $result = self::$repository->getByName('Linux'); - $data = $result->getData(); - - $this->assertEquals(2, $data->getId()); - $this->assertEquals('Linux server', $data->getDescription()); - - // Se comprueba que el hash generado es el mismo en para el nombre 'Web' - $result = self::$repository->getByName(' web. '); - $data = $result->getData(); - - $this->assertEquals(1, $data->getId()); - $this->assertEquals('Web sites', $data->getDescription()); - } - - /** - * Comprobar la búsqueda mediante texto - * - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('linux'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(2, $data[0]->id); - $this->assertEquals('Linux server', $data[0]->description); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('prueba'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $data); - } - - /** - * Comprobar los resultados de obtener las categorías por Id - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $this->assertEquals(0, self::$repository->getById(10)->getNumRows()); - - $result = self::$repository->getById(1); - $data = $result->getData(); - - $this->assertEquals('Web', $data->getName()); - $this->assertEquals('Web sites', $data->getDescription()); - - $result = self::$repository->getById(2); - $data = $result->getData(); - - $this->assertEquals('Linux', $data->getName()); - $this->assertEquals('Linux server', $data->getDescription()); - } - - /** - * Comprobar la obtención de todas las categorías - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $count = self::getRowCount('Category'); - - $result = self::$repository->getAll(); - $this->assertEquals($count, $result->getNumRows()); - - /** @var CategoryData[] $data */ - $data = $result->getDataAsArray(); - $this->assertCount($count, $data); - - $this->assertInstanceOf(CategoryData::class, $data[0]); - $this->assertEquals('Linux', $data[0]->getName()); - - $this->assertInstanceOf(CategoryData::class, $data[1]); - $this->assertEquals('SSH', $data[1]->getName()); - - $this->assertInstanceOf(CategoryData::class, $data[2]); - $this->assertEquals('Web', $data[2]->getName()); - } - - /** - * Comprobar la actualización de categorías - * - * @throws ConstraintException - * @throws QueryException - * @throws SPException - * @throws DuplicatedItemException - */ - public function testUpdate() - { - $categoryData = new CategoryData(); - $categoryData->id = 1; - $categoryData->name = 'Web prueba'; - $categoryData->description = 'Descripción web prueba'; - - self::$repository->update($categoryData); - - $result = self::$repository->getById(1); - $data = $result->getData(); - - $this->assertEquals($categoryData->name, $data->getName()); - $this->assertEquals($categoryData->description, $data->getDescription()); - - // Comprobar la a actualización con un nombre duplicado comprobando su hash - $categoryData = new CategoryData(); - $categoryData->id = 1; - $categoryData->name = ' linux.'; - - $this->expectException(DuplicatedItemException::class); - - self::$repository->update($categoryData); - } - - /** - * Comprobar la eliminación de categorías - * - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $countBefore = self::getRowCount('Category'); - - $this->assertEquals(1, self::$repository->deleteByIdBatch([3])); - - $countAfter = self::getRowCount('Category'); - - $this->assertEquals($countBefore - 1, $countAfter); - - // Comprobar que se produce una excepción al tratar de eliminar categorías usadas - $this->expectException(ConstraintException::class); - - $this->assertEquals(1, self::$repository->deleteByIdBatch([1, 2, 3])); - } - - /** - * Comprobar la creación de categorías - * - * @throws DuplicatedItemException - * @throws SPException - */ - public function testCreate() - { - $countBefore = self::getRowCount('Category'); - - $categoryData = new CategoryData(); - $categoryData->name = 'Categoría prueba'; - $categoryData->description = 'Descripción prueba'; - - $id = self::$repository->create($categoryData); - - // Comprobar que el Id devuelto corresponde con la categoría creada - $result = self::$repository->getById($id); - $data = $result->getData(); - - $this->assertEquals($categoryData->name, $data->getName()); - - $countAfter = self::getRowCount('Category'); - - $this->assertEquals($countBefore + 1, $countAfter); - } - - /** - * Comprobar la eliminación de categorías por Id - * - * @throws QueryException - * @throws ConstraintException - */ - public function testDelete() - { - $countBefore = self::getRowCount('Category'); - - $this->assertEquals(1, self::$repository->delete(3)); - - $countAfter = self::getRowCount('Category'); - - $this->assertEquals($countBefore - 1, $countAfter); - - // Comprobar que se produce una excepción al tratar de eliminar categorías usadas - $this->expectException(ConstraintException::class); - - $this->assertEquals(1, self::$repository->delete(2)); - } - - /** - * Comprobar la obtención de categorías por Id en lote - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch() - { - $this->assertCount(3, self::$repository->getByIdBatch([1, 2, 3])->getDataAsArray()); - $this->assertCount(3, self::$repository->getByIdBatch([1, 2, 3, 4, 5])->getDataAsArray()); - $this->assertCount(0, self::$repository->getByIdBatch([])->getDataAsArray()); - } -} diff --git a/tests/SPT/Repositories/ClientRepositoryTest.php b/tests/SPT/Repositories/ClientRepositoryTest.php deleted file mode 100644 index ae9bf6ad..00000000 --- a/tests/SPT/Repositories/ClientRepositoryTest.php +++ /dev/null @@ -1,312 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ClientData; -use SP\DataModel\ItemSearchData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Infrastructure\Client\Repositories\ClientRepository; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Mvc\Model\QueryCondition; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class ClientRepositoryTest - * - * Tests de integración para comprobar las consultas a la BBDD relativas a los clientes - * - * @package SPT - */ -class ClientRepositoryTest extends DatabaseTestCase -{ - /** - * @var ClientRepository - */ - private static $repository; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(ClientRepository::class); - } - - /** - * Comprobar los resultados de obtener los cliente por nombre - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByName() - { - $this->assertNull(self::$repository->getByName('Spotify')->getData()); - - $data = self::$repository->getByName('Google')->getData(); - - $this->assertEquals(1, $data->getId()); - $this->assertEquals('Google Inc.', $data->getDescription()); - - $data = self::$repository->getByName('Apple')->getData(); - - $this->assertEquals(2, $data->getId()); - $this->assertEquals('Apple Inc.', $data->getDescription()); - - // Se comprueba que el hash generado es el mismo en para el nombre 'Web' - $data = self::$repository->getByName(' google. ')->getData(); - - $this->assertEquals(1, $data->getId()); - $this->assertEquals('Google Inc.', $data->getDescription()); - } - - /** - * Comprobar la búsqueda mediante texto - * - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('google'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(ClientData::class, $data[0]); - $this->assertEquals(1, $data[0]->id); - $this->assertEquals('Google Inc.', $data[0]->description); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('prueba'); - - $result = self::$repository->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $result->getDataAsArray()); - } - - /** - * Comprobar los resultados de obtener los clientes por Id - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $this->assertNull(self::$repository->getById(10)->getData()); - - $data = self::$repository->getById(1)->getData(); - - $this->assertEquals('Google', $data->getName()); - $this->assertEquals('Google Inc.', $data->getDescription()); - - $data = self::$repository->getById(2)->getData(); - - $this->assertEquals('Apple', $data->getName()); - $this->assertEquals('Apple Inc.', $data->getDescription()); - } - - /** - * Comprobar la obtención de todas las client - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $count = self::getRowCount('Client'); - - $results = self::$repository->getAll(); - /** @var ClientData[] $data */ - $data = $results->getDataAsArray(); - - $this->assertCount($count, $data); - - $this->assertInstanceOf(ClientData::class, $data[0]); - $this->assertEquals('Amazon', $data[0]->getName()); - - $this->assertInstanceOf(ClientData::class, $data[1]); - $this->assertEquals('Apple', $data[1]->getName()); - - $this->assertInstanceOf(ClientData::class, $data[2]); - $this->assertEquals('Google', $data[2]->getName()); - - $this->assertInstanceOf(ClientData::class, $data[3]); - $this->assertEquals('Microsoft', $data[3]->getName()); - } - - /** - * Comprobar la actualización de clientes - * - * @throws ConstraintException - * @throws QueryException - * @throws SPException - * @throws DuplicatedItemException - */ - public function testUpdate() - { - $data = new ClientData(); - $data->id = 1; - $data->name = 'Cliente prueba'; - $data->description = 'Descripción cliente prueba'; - - self::$repository->update($data); - - $result = self::$repository->getById(1)->getData(); - - $this->assertEquals($data->name, $result->getName()); - $this->assertEquals($data->description, $result->getDescription()); - - // Comprobar la a actualización con un nombre duplicado comprobando su hash - $data = new ClientData(); - $data->id = 1; - $data->name = ' apple.'; - - $this->expectException(DuplicatedItemException::class); - - self::$repository->update($data); - } - - /** - * Comprobar la eliminación de clientes - * - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $countBefore = self::getRowCount('Client'); - - $this->assertEquals(1, self::$repository->deleteByIdBatch([4])); - - $countAfter = self::getRowCount('Client'); - - $this->assertEquals($countBefore - 1, $countAfter); - - // Comprobar que se produce una excepción al tratar de eliminar clientes usados - $this->expectException(ConstraintException::class); - - $this->assertEquals(1, self::$repository->deleteByIdBatch([1, 2, 3])); - } - - /** - * Comprobar la creación de clientes - * - * @throws DuplicatedItemException - * @throws SPException - */ - public function testCreate() - { - $countBefore = self::getRowCount('Client'); - - $data = new ClientData(); - $data->name = 'Cliente prueba'; - $data->description = 'Descripción prueba'; - $data->isGlobal = 1; - - $id = self::$repository->create($data); - - // Comprobar que el Id devuelto corresponde con el cliente creado - /** @var ClientData $result */ - $result = self::$repository->getById($id)->getData(); - - $this->assertEquals($data->name, $result->getName()); - $this->assertEquals($data->isGlobal, $result->getIsGlobal()); - - $countAfter = self::getRowCount('Client'); - - $this->assertEquals($countBefore + 1, $countAfter); - - $this->expectException(DuplicatedItemException::class); - - self::$repository->create($data); - } - - /** - * Comprobar la eliminación de clientes por Id - * - * @throws QueryException - * @throws ConstraintException - */ - public function testDelete() - { - $countBefore = self::getRowCount('Client'); - - $this->assertEquals(1, self::$repository->delete(4)); - - $countAfter = self::getRowCount('Client'); - - $this->assertEquals($countBefore - 1, $countAfter); - - // Comprobar que se produce una excepción al tratar de eliminar clientes usados - $this->expectException(ConstraintException::class); - - $this->assertEquals(1, self::$repository->delete(2)); - } - - /** - * Comprobar la obtención de clientes por Id en lote - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch(): void - { - $this->assertCount(3, self::$repository->getByIdBatch([1, 2, 3])->getDataAsArray()); - $this->assertCount(4, self::$repository->getByIdBatch([1, 2, 3, 4, 5])->getDataAsArray()); - $this->assertCount(0, self::$repository->getByIdBatch([])->getDataAsArray()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllForFilter() - { - $filter = new QueryCondition(); - $filter->addFilter('Account.isPrivate = 0'); - - $this->assertEquals(4, self::$repository->getAllForFilter($filter)->getNumRows()); - } -} diff --git a/tests/SPT/Repositories/ConfigRepositoryTest.php b/tests/SPT/Repositories/ConfigRepositoryTest.php deleted file mode 100644 index fda96480..00000000 --- a/tests/SPT/Repositories/ConfigRepositoryTest.php +++ /dev/null @@ -1,162 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ConfigData; -use SP\Domain\Config\Ports\ConfigRepositoryInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Infrastructure\Config\Repositories\ConfigRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class ConfigRepositoryTest - * - * @package SPT\Repositories - */ -class ConfigRepositoryTest extends DatabaseTestCase -{ - /** - * @var ConfigRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(ConfigRepository::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCreate() - { - $data = new ConfigData('test', uniqid()); - - $this->assertEquals(1, self::$repository->create($data)); - - $result = self::$repository->getByParam($data->getParameter()); - $this->assertEquals(1, $result->getNumRows()); - - $resultData = $result->getData(); - - $this->assertEquals($data->getParameter(), $resultData->parameter); - $this->assertEquals($data->getValue(), $resultData->value); - - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testHas() - { - $this->assertTrue(self::$repository->has('config_backup_date')); - $this->assertFalse(self::$repository->has('test')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdate() - { - $data = new ConfigData('config_backup_date', time()); - - $this->assertEquals(1, self::$repository->update($data)); - - $result = self::$repository->getByParam($data->getParameter()); - $this->assertEquals(1, $result->getNumRows()); - - $resultData = $result->getData(); - - $this->assertEquals($data->getParameter(), $resultData->parameter); - $this->assertEquals($data->getValue(), $resultData->value); - - $data = new ConfigData('test', time()); - - $this->assertEquals(0, self::$repository->update($data)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $result = self::$repository->getAll(); - - $this->assertEquals(self::getRowCount('Config'), $result->getNumRows()); - - $data = $result->getDataAsArray(); - - $this->assertEquals('config_backup', $data[0]->parameter); - $this->assertEquals('789ca558db6edb3810edb718c5be6c6b88ba4b45814de3a497a48d374e832cb0404191944d589654916a9216f9f71d5292633ba1a4621f628bf11cce68e6cc85bc886d2b9e2ce6ff1e1779ca97edd70c4b3c89c328fe2562c78e272f9e13785197cb0a5376c6ee276f440cdba82f273089d3625ddff2353fc97192313a79c3634b019c21c0d72afb2d0520ff0e0bb68b7107318255bf059863217601d110e00bde305162b2675768426514973396e23a93efaba22e95b710205c6b04625e1529cf588731bf4c591577f7a3e3a1a517acfab1ef2ad42b3f2f2aa9b60eadd01a963e0cc3c0de0731307ab3ac938ce76bf119df5d73762b94414e2f977610577ca35de95bd628c88e3ffbbd8f0929ea5c1eab0fada0d7fbadf439a818de9aac18597f2d29964c6c03db2f9d1792931d6963da13fdf8018bd5a42524b6701a440125a1635386b01721124436b27c9fb1d0775ddb4d9dc8f394bc6d0c124d3e14422a1904968a7b4816215ed3e435653f74788dd4a7c9a2206b2677b8d0a74665a29209b65a86101dd1901f4f2e681cf0facbf787e4e5d9fd59fc6b08db515a6145f9cd4b506061d7717c8cc9a0de36791cc752e4b0cda58f25f5724445659be230dd8dea550911475956dc327a7227c101384661fcabc5c593f9ec74cbc478f269fe5eadec66f5fee3e936c940f28bfecd6d5617b32bb5f2bad5624bfe7832bb3856ab40314baf6e74f1687ebc39d7a251bb5a9c6bf5ad35d78b995eb6e65cdd6825a8b5e77871ad97ad41ef8ecef4b2b5e87236d7cbd6a4b3937ff4b2b5e9f8b2d92a68f57e06bd0f633db7e03f9b426cd96e6f126ad0e8dab1cc8a04670b862bb2da86d2582d792e24ce7637ee6d235df7b481b294bc55ac41afe021ad18e325568f45b5ecef937a1f9ed38efe1e70b7e6f42da61b9ebf22f9db1a7e10eaa12d6ce2d5ff55d56529b4e205231593c87634d2eb43ce9feb3bc60c5288830cb28dad5f091f51311c1f25d8b6f9471b8c0558493fb6611b76054f4db5eba6addfa6a39ca6de1a4b598dd35a2c0fd9697e1f90fdc1f2a666d85dc900064054a0254dbb1d2030ca8e69934fc6eab6c13c3baae58a8d9d5414e0d05823e395f069556cba220d2d53fed53686ad1f7bd1dbf600cefbe3d3cbdbb5fc13fdbd621723906d81b755e5718dfe54a297ec7b0d9689c3fa6d8cb002411ed41597f7a322dc003a5e2957a8ff4c7fcb15bbddee5947fafdef4878c93be2a08e38cf6ff630f42e8f14dceeb44fb83efee412d8961336ec6765d16d51d105cef404e28383528a2c2f24d84a129c467e40ad10852ea3b6cd984d42eaf98107bf92089e228252db09e02f85f19da6fd6eaa9880095f1c89635ced9416a3bc6042f02257436c51cba6253683ac318e824b768e731d2f7030cbfb4771257eb562cd4c851cc51ac92a8eb3d74956b3fe02dccc92d7d009c0c62e851ccb9aa2d0f21c64a181131f7c24d0ac86363006fab9f3a891534af894677264ab684e894b56ef1f5f8dbe50f24d433f400c4ce2f0d84c18f0be8ee7f8be1a795c23a83ba67cdc806d8745d2f8320926ebbafcb6da99fa49845c3b0ac324a211c28e2274e83861905a5ee49000239be1d4c376bf97d85d0935707f633742294e08248b150528f1121b411e3976e0fbd8713d0b0784fa76d2dfe05652964f8aa5d1f95059f61b9cd55b901bf14b68b9928d2ec80de8e901da18aa06d0f5084f4fabe60b80768e52cde8aad0d11d6e940d8316b8b508dca3e7b3fe12c47252dd9772d15496edcdc4d039f7b4ce323de41c1138678a2de78c633486960fa32827072c758df5608b8069a1382f963c3f24f8307456a8ea3feac24988e2b93b1af35dd023e0e08ac69caeadf34eee4a5e3d4957a3a23d547781812cc70f2d28fe0fff0152be6bea', $data[0]->value); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByParam() - { - $result = self::$repository->getByParam('config_backup_date'); - $this->assertEquals(1, $result->getNumRows()); - - $resultData = $result->getData(); - - $this->assertEquals('config_backup_date', $resultData->parameter); - $this->assertEquals('1531353681', $resultData->value); - - $result = self::$repository->getByParam('test'); - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByParam() - { - $this->assertEquals(1, self::$repository->deleteByParam('tempmaster_passtime')); - $this->assertEquals(0, self::$repository->deleteByParam('test')); - } -} diff --git a/tests/SPT/Repositories/CustomFieldDefRepositoryTest.php b/tests/SPT/Repositories/CustomFieldDefRepositoryTest.php deleted file mode 100644 index c7df52e6..00000000 --- a/tests/SPT/Repositories/CustomFieldDefRepositoryTest.php +++ /dev/null @@ -1,297 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\CustomFieldDefinitionData; -use SP\DataModel\ItemSearchData; -use SP\Domain\Core\Acl\AclActionsInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\CustomField\Ports\CustomFieldDefRepositoryInterface; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SP\Infrastructure\CustomField\Repositories\CustomFieldDefRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class CustomFieldDefRepositoryTest - * - * @package SPT\Repositories - */ -class CustomFieldDefRepositoryTest extends DatabaseTestCase -{ - /** - * @var CustomFieldDefRepositoryInterface - */ - private static $repository; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(CustomFieldDefRepository::class); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetById() - { - $expected = new CustomFieldDefinitionData(); - $expected->setId(1); - $expected->setName('Prueba'); - $expected->setIsEncrypted(1); - $expected->setHelp('Ayuda'); - $expected->setModuleId(AclActionsInterface::ACCOUNT); - $expected->setRequired(true); - $expected->setTypeId(1); - $expected->setShowInList(0); - - $this->assertEquals($expected, self::$repository->getById(1)); - - $this->expectException(NoSuchItemException::class); - - $this->assertEquals($expected, self::$repository->getById(10)); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testUpdate() - { - $data = new CustomFieldDefinitionData(); - $data->setId(1); - $data->setName('PIN'); - $data->setIsEncrypted(0); - $data->setHelp('Pin code'); - $data->setModuleId(AclActionsInterface::CLIENT); - $data->setRequired(false); - $data->setTypeId(2); - $data->setShowInList(1); - - $this->assertEquals(1, self::$repository->update($data)); - - $dataUpdated = self::$repository->getById(1); - - $this->assertEquals($data, $dataUpdated); - - $data->setTypeId(100); - - $this->expectException(ConstraintException::class); - - $this->assertEquals(1, self::$repository->update($data)); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(1, self::$repository->deleteByIdBatch([3, 4])); - $this->assertEquals(2, self::getRowCount('CustomFieldDefinition')); - $this->assertEquals(0, self::$repository->deleteByIdBatch([])); - - $this->expectException(ConstraintException::class); - - self::$repository->deleteByIdBatch([1, 2]); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch() - { - $result = self::$repository->getByIdBatch([1, 2]); - - $this->assertEquals(2, $result->getNumRows()); - - $data = $result->getDataAsArray(); - - $this->assertCount(2, $data); - $this->assertInstanceOf(CustomFieldDefinitionData::class, $data[0]); - $this->assertInstanceOf(CustomFieldDefinitionData::class, $data[1]); - - $expected = new CustomFieldDefinitionData(); - $expected->setId(1); - $expected->setName('Prueba'); - $expected->setIsEncrypted(1); - $expected->setHelp('Ayuda'); - $expected->setModuleId(AclActionsInterface::ACCOUNT); - $expected->setRequired(true); - $expected->setTypeId(1); - $expected->setShowInList(0); - - $this->assertEquals($expected, $data[0]); - - $expected = new CustomFieldDefinitionData(); - $expected->setId(2); - $expected->setName('RSA'); - $expected->setIsEncrypted(0); - $expected->setModuleId(AclActionsInterface::CATEGORY); - $expected->setRequired(false); - $expected->setTypeId(2); - $expected->setShowInList(0); - - $this->assertEquals($expected, $data[1]); - - $this->assertEquals(0, self::$repository->getByIdBatch([10])->getNumRows()); - - $this->assertEquals(0, self::$repository->getByIdBatch([])->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testCreate() - { - $data = new CustomFieldDefinitionData(); - $data->setId(4); - $data->setName('Phone'); - $data->setIsEncrypted(0); - $data->setHelp('Telefono'); - $data->setModuleId(AclActionsInterface::ACCOUNT); - $data->setRequired(true); - $data->setTypeId(6); - $data->setShowInList(0); - - $this->assertEquals(4, self::$repository->create($data)); - - $this->assertEquals($data, self::$repository->getById(4)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - self::$repository->resetCollection(); - - $result = self::$repository->getAll(); - $this->assertEquals(3, $result->getNumRows()); - - $data = $result->getDataAsArray(); - - $this->assertCount(3, $data); - - $expected = new CustomFieldDefinitionData(); - $expected->setId(1); - $expected->setName('Prueba'); - $expected->setIsEncrypted(1); - $expected->setHelp('Ayuda'); - $expected->setModuleId(AclActionsInterface::ACCOUNT); - $expected->setRequired(true); - $expected->setTypeId(1); - $expected->setShowInList(0); - - $this->assertEquals($expected, $data[0]); - - $expected = new CustomFieldDefinitionData(); - $expected->setId(2); - $expected->setName('RSA'); - $expected->setIsEncrypted(0); - $expected->setModuleId(AclActionsInterface::CATEGORY); - $expected->setRequired(false); - $expected->setTypeId(2); - $expected->setShowInList(0); - - $this->assertEquals($expected, $data[1]); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setSeachString('RSA'); - $itemSearchData->setLimitCount(10); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertEquals(1, $result->getTotalNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(CustomFieldDefinitionData::class, $data[0]); - $this->assertEquals(2, $data[0]->id); - $this->assertEquals('password', $data[0]->typeName); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setSeachString('test'); - $itemSearchData->setLimitCount(10); - - $this->assertEquals(0, self::$repository->search($itemSearchData)->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDelete() - { - $this->assertEquals(1, self::$repository->delete(3)); - $this->assertEquals(0, self::$repository->delete(10)); - $this->assertEquals(2, self::getRowCount('CustomFieldDefinition')); - - $this->expectException(ConstraintException::class); - - self::$repository->delete(1); - } - - /** - * Performs operation returned by getSetUpOperation(). - */ - protected function setUp(): void - { - parent::setUp(); - - self::$repository->resetCollection(); - } -} diff --git a/tests/SPT/Repositories/CustomFieldRepositoryTest.php b/tests/SPT/Repositories/CustomFieldRepositoryTest.php deleted file mode 100644 index 77437887..00000000 --- a/tests/SPT/Repositories/CustomFieldRepositoryTest.php +++ /dev/null @@ -1,410 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\CustomFieldData; -use SP\Domain\Core\Acl\AclActionsInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\CustomField\Ports\CustomFieldRepositoryInterface; -use SP\Infrastructure\CustomField\Repositories\CustomFieldRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class CustomFieldRepositoryTest - * - * @package SPT\Repositories - */ -class CustomFieldRepositoryTest extends DatabaseTestCase -{ - /** - * @var CustomFieldRepositoryInterface - */ - private static $repository; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(CustomFieldRepository::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteCustomFieldDataBatch() - { - $this->assertEquals(2, self::$repository->deleteCustomFieldDataBatch([1, 2, 3], AclActionsInterface::ACCOUNT)); - - $this->assertEquals(1, self::$repository->deleteCustomFieldDataBatch([1, 2, 3], AclActionsInterface::CATEGORY)); - - $this->assertEquals(0, self::getRowCount('CustomFieldData')); - - $this->assertEquals(0, self::$repository->deleteCustomFieldDataBatch([], AclActionsInterface::CATEGORY)); - - $this->assertEquals(0, self::$repository->deleteCustomFieldDataBatch([], AclActionsInterface::USER)); - - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteCustomFieldDataForDefinition() - { - $this->assertEquals(1, self::$repository->deleteCustomFieldDataForDefinition(1, AclActionsInterface::ACCOUNT, 1)); - $this->assertEquals(0, self::$repository->deleteCustomFieldDataForDefinition(1, AclActionsInterface::ACCOUNT, 2)); - $this->assertEquals(0, self::$repository->deleteCustomFieldDataForDefinition(10, AclActionsInterface::ACCOUNT, 3)); - - $this->assertEquals(1, self::$repository->deleteCustomFieldDataForDefinition(1, AclActionsInterface::CATEGORY, 2)); - $this->assertEquals(0, self::$repository->deleteCustomFieldDataForDefinition(1, AclActionsInterface::CATEGORY, 1)); - $this->assertEquals(0, self::$repository->deleteCustomFieldDataForDefinition(10, AclActionsInterface::CATEGORY, 3)); - - $this->assertEquals(0, self::$repository->deleteCustomFieldDataForDefinition(1, AclActionsInterface::USER, 1)); - $this->assertEquals(0, self::$repository->deleteCustomFieldDataForDefinition(1, AclActionsInterface::USER, 2)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCheckExists() - { - $data = new CustomFieldData(); - $data->setModuleId(AclActionsInterface::ACCOUNT); - $data->setDefinitionId(1); - $data->setId(1); - - $this->assertFalse(self::$repository->checkExists($data)); - - $data->setModuleId(AclActionsInterface::CATEGORY); - $data->setDefinitionId(1); - $data->setId(1); - - $this->assertFalse(self::$repository->checkExists($data)); - - $data->setModuleId(AclActionsInterface::USER); - $data->setDefinitionId(1); - $data->setId(1); - - $this->assertFalse(self::$repository->checkExists($data)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllEncrypted() - { - $result = self::$repository->getAllEncrypted(); - $this->assertEquals(2, $result->getNumRows()); - - /** @var CustomFieldData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertCount(2, $data); - $this->assertInstanceOf(CustomFieldData::class, $data[0]); - $this->assertEquals(1, $data[0]->getItemId()); - $this->assertEquals(AclActionsInterface::ACCOUNT, $data[0]->getModuleId()); - $this->assertEquals(1, $data[0]->getItemId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteCustomFieldDefinitionDataBatch() - { - $this->assertEquals(3, self::$repository->deleteCustomFieldDefinitionDataBatch([1, 2, 3])); - - $this->assertEquals(0, self::getRowCount('CustomFieldData')); - - $this->assertEquals(0, self::$repository->deleteCustomFieldDefinitionDataBatch([])); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $result = self::$repository->getAll(); - $this->assertEquals(3, $result->getNumRows()); - - $data = $result->getDataAsArray(); - - $this->assertCount(3, $data); - $this->assertInstanceOf(CustomFieldData::class, $data[0]); - $this->assertInstanceOf(CustomFieldData::class, $data[1]); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteCustomFieldData() - { - $this->assertEquals(1, self::$repository->deleteCustomFieldData(1, AclActionsInterface::ACCOUNT)); - $this->assertEquals(1, self::$repository->deleteCustomFieldData(1, AclActionsInterface::CATEGORY)); - - $this->assertEquals(1, self::getRowCount('CustomFieldData')); - - $this->assertEquals(1, self::$repository->deleteCustomFieldData(2, AclActionsInterface::ACCOUNT)); - - $this->assertEquals(0, self::$repository->deleteCustomFieldData(2, AclActionsInterface::CATEGORY)); - - $this->assertEquals(0, self::$repository->deleteCustomFieldData(2, AclActionsInterface::USER)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetForModuleById() - { - $result = self::$repository->getForModuleAndItemId(AclActionsInterface::ACCOUNT, 1); - $this->assertEquals(1, $result->getNumRows()); - - $data = $result->getDataAsArray(); - - $this->assertCount(1, $data); - $this->assertEquals('Prueba', $data[0]->definitionName); - $this->assertEquals(1, $data[0]->definitionId); - $this->assertEquals(AclActionsInterface::ACCOUNT, $data[0]->moduleId); - $this->assertEquals(1, $data[0]->required); - $this->assertEquals(0, $data[0]->showInList); - $this->assertEquals('Ayuda', $data[0]->help); - $this->assertEquals(1, $data[0]->isEncrypted); - $this->assertEquals(1, $data[0]->typeId); - $this->assertEquals('text', $data[0]->typeName); - $this->assertEquals('Texto', $data[0]->typeText); - $this->assertNotEmpty($data[0]->data); - $this->assertNotEmpty($data[0]->key); - - $result = self::$repository->getForModuleAndItemId(AclActionsInterface::ACCOUNT, 2); - $this->assertEquals(1, $result->getNumRows()); - $data = $result->getDataAsArray(); - - $this->assertCount(1, $data); - $this->assertEquals('Prueba', $data[0]->definitionName); - $this->assertEquals(1, $data[0]->definitionId); - $this->assertEquals(AclActionsInterface::ACCOUNT, $data[0]->moduleId); - $this->assertEquals(1, $data[0]->required); - $this->assertEquals(0, $data[0]->showInList); - $this->assertEquals('Ayuda', $data[0]->help); - $this->assertEquals(1, $data[0]->isEncrypted); - $this->assertEquals(1, $data[0]->typeId); - $this->assertEquals('text', $data[0]->typeName); - $this->assertEquals('Texto', $data[0]->typeText); - $this->assertNotNull($data[0]->data); - $this->assertNotNull($data[0]->key); - - $result = self::$repository->getForModuleAndItemId(AclActionsInterface::ACCOUNT, 3); - - $this->assertEquals(1, $result->getNumRows()); - - $result = self::$repository->getForModuleAndItemId(AclActionsInterface::CATEGORY, 1); - $this->assertEquals(2, $result->getNumRows()); - - $data = $result->getDataAsArray(); - - $this->assertCount(2, $data); - $this->assertEquals('SSL', $data[0]->definitionName); - $this->assertEquals(3, $data[0]->definitionId); - $this->assertEquals(AclActionsInterface::CATEGORY, $data[0]->moduleId); - $this->assertEquals(0, $data[0]->required); - $this->assertEquals(0, $data[0]->showInList); - $this->assertEquals(null, $data[0]->help); - $this->assertEquals(1, $data[0]->isEncrypted); - $this->assertEquals(10, $data[0]->typeId); - $this->assertEquals('textarea', $data[0]->typeName); - $this->assertEquals('Área de Texto', $data[0]->typeText); - $this->assertNull($data[0]->data); - $this->assertNull($data[0]->key); - - $result = self::$repository->getForModuleAndItemId(AclActionsInterface::CATEGORY, 2); - $this->assertEquals(2, $result->getNumRows()); - - $data = $result->getDataAsArray(); - - $this->assertCount(2, $data); - $this->assertEquals('SSL', $data[0]->definitionName); - $this->assertEquals(3, $data[0]->definitionId); - $this->assertEquals(AclActionsInterface::CATEGORY, $data[0]->moduleId); - $this->assertEquals(0, $data[0]->required); - $this->assertEquals(0, $data[0]->showInList); - $this->assertEquals(null, $data[0]->help); - $this->assertEquals(1, $data[0]->isEncrypted); - $this->assertEquals(10, $data[0]->typeId); - $this->assertEquals('textarea', $data[0]->typeName); - $this->assertEquals('Área de Texto', $data[0]->typeText); - $this->assertNull($data[0]->data); - $this->assertNull($data[0]->key); - - $result = self::$repository->getForModuleAndItemId(AclActionsInterface::CATEGORY, 3); - $this->assertEquals(2, $result->getNumRows()); - - $result = self::$repository->getForModuleAndItemId(AclActionsInterface::USER, 1); - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCreate() - { - $data = new CustomFieldData(); - $data->setId(2); - $data->setModuleId(AclActionsInterface::ACCOUNT); - $data->setDefinitionId(1); - $data->setData('cuenta'); - $data->setKey('nan'); - - $this->assertEquals(4, self::$repository->create($data)); - - $data = new CustomFieldData(); - $data->setId(2); - $data->setModuleId(AclActionsInterface::CATEGORY); - $data->setDefinitionId(2); - $data->setData('categoria'); - $data->setKey('nan'); - - $this->assertEquals(5, self::$repository->create($data)); - - $this->expectException(ConstraintException::class); - - $data = new CustomFieldData(); - $data->setId(2); - $data->setModuleId(AclActionsInterface::ACCOUNT); - $data->setDefinitionId(1); - $data->setData('cuenta'); - $data->setKey('nan'); - - self::$repository->create($data); - - $data->setDefinitionId(3); - - self::$repository->create($data); - - $data = new CustomFieldData(); - $data->setId(2); - $data->setModuleId(AclActionsInterface::CATEGORY); - $data->setDefinitionId(2); - $data->setData('categoria'); - $data->setKey('nan'); - - self::$repository->create($data); - - $data->setDefinitionId(4); - - self::$repository->create($data); - - $this->assertEquals(4, self::getRowCount('CustomFieldData')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteCustomFieldDefinitionData() - { - $this->assertEquals(2, self::$repository->deleteCustomFieldDefinitionData(1)); - $this->assertEquals(1, self::$repository->deleteCustomFieldDefinitionData(2)); - - $this->assertEquals(0, self::getRowCount('CustomFieldData')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdate() - { - $data = new CustomFieldData(); - $data->setId(1); - $data->setModuleId(AclActionsInterface::ACCOUNT); - $data->setDefinitionId(1); - $data->setData('cuenta'); - $data->setKey('nan'); - - $this->assertEquals(0, self::$repository->update($data)); - - $data = new CustomFieldData(); - $data->setId(1); - $data->setModuleId(AclActionsInterface::CATEGORY); - $data->setDefinitionId(2); - $data->setData('categoria'); - $data->setKey('nan'); - - $this->assertEquals(0, self::$repository->update($data)); - - - $data = new CustomFieldData(); - $data->setId(2); - $data->setModuleId(AclActionsInterface::ACCOUNT); - $data->setDefinitionId(1); - $data->setData('cuenta'); - $data->setKey('nan'); - - $this->assertEquals(0, self::$repository->update($data)); - - $data = new CustomFieldData(); - $data->setId(2); - $data->setModuleId(AclActionsInterface::CATEGORY); - $data->setDefinitionId(2); - $data->setData('categoria'); - $data->setKey('nan'); - - $this->assertEquals(0, self::$repository->update($data)); - - $this->assertEquals(0, self::$repository->update(new CustomFieldData())); - - $data = new CustomFieldData(); - $data->setId(2); - $data->setModuleId(AclActionsInterface::USER); - $data->setDefinitionId(3); - $data->setData('nan'); - $data->setKey('nan'); - - $this->assertEquals(0, self::$repository->update($data)); - - $this->assertEquals(3, self::getRowCount('CustomFieldData')); - } -} diff --git a/tests/SPT/Repositories/CustomFieldTypeRepositoryTest.php b/tests/SPT/Repositories/CustomFieldTypeRepositoryTest.php deleted file mode 100644 index 706a9703..00000000 --- a/tests/SPT/Repositories/CustomFieldTypeRepositoryTest.php +++ /dev/null @@ -1,175 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\CustomFieldTypeData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\CustomField\Ports\CustomFieldTypeRepositoryInterface; -use SP\Infrastructure\CustomField\Repositories\CustomFieldTypeRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class CustomFieldTypeRepositoryTest - * - * @package SPT\Repositories - */ -class CustomFieldTypeRepositoryTest extends DatabaseTestCase -{ - /** - * @var CustomFieldTypeRepositoryInterface - */ - private static $repository; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(CustomFieldTypeRepository::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $countBefore = self::getRowCount('CustomFieldType'); - - $this->assertEquals(2, self::$repository->deleteByIdBatch([3, 4, 100])); - $this->assertEquals(0, self::$repository->deleteByIdBatch([])); - $this->assertEquals($countBefore - 2, self::getRowCount('CustomFieldType')); - - $this->expectException(ConstraintException::class); - - self::$repository->deleteByIdBatch([1, 2]); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDelete() - { - $countBefore = self::getRowCount('CustomFieldType'); - - $this->assertEquals(1, self::$repository->delete(3)); - $this->assertEquals(0, self::$repository->delete(100)); - $this->assertEquals($countBefore - 1, self::getRowCount('CustomFieldType')); - - $this->expectException(ConstraintException::class); - - self::$repository->delete(1); - self::$repository->delete(2); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $result = self::$repository->getAll(); - - $this->assertEquals(10, $result->getNumRows()); - - /** @var CustomFieldTypeData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertCount(10, $data); - $this->assertInstanceOf(CustomFieldTypeData::class, $data[0]); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals('text', $data[0]->getName()); - $this->assertEquals('Texto', $data[0]->getText()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $data = new CustomFieldTypeData(); - $data->setId(10); - $data->setName('textarea'); - $data->setText('Área de Texto'); - - $result = self::$repository->getById(10); - - $this->assertEquals(1, $result->getNumRows()); - - $this->assertEquals($data, $result->getData()); - - $this->assertEquals(0, self::$repository->getById(11)->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testCreate() - { - $data = new CustomFieldTypeData(); - $data->setId(11); - $data->setName('prueba'); - $data->setText('Prueba'); - - $this->assertEquals(11, self::$repository->create($data)); - - $this->assertEquals($data, self::$repository->getById(11)->getData()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdate() - { - $data = new CustomFieldTypeData(); - $data->setId(10); - $data->setName('prueba'); - $data->setText('Prueba'); - - $this->assertEquals(1, self::$repository->update($data)); - - $this->assertEquals($data, self::$repository->getById(10)->getData()); - } -} diff --git a/tests/SPT/Repositories/EventlogRepositoryTest.php b/tests/SPT/Repositories/EventlogRepositoryTest.php deleted file mode 100644 index 5f5ce9d4..00000000 --- a/tests/SPT/Repositories/EventlogRepositoryTest.php +++ /dev/null @@ -1,157 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\EventlogData; -use SP\DataModel\ItemSearchData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Security\Ports\EventlogRepositoryInterface; -use SP\Infrastructure\Security\Repositories\EventlogRepository; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class EventlogRepositoryTest - * - * Tests de integración para comprobar las consultas a la BBDD relativas a los registros de eventos - * - * @package SPT - */ -class EventlogRepositoryTest extends DatabaseTestCase -{ - /** - * @var EventlogRepositoryInterface - */ - private static $repository; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(EventlogRepository::class); - } - - /** - * Comprobar la búsqueda de eventos por texto - * - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('login.auth.database'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(4, $result->getNumRows()); - $this->assertCount(4, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals('login.auth.database', $data[0]->action); - - $itemSearchData->setSeachString('login.auth.'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(4, $result->getNumRows()); - $this->assertCount(4, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - - $itemSearchData->setSeachString('Tiempo inactivo : 0 min.'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - - $itemSearchData->setSeachString('prueba'); - - $result = self::$repository->search($itemSearchData); - - $this->assertCount(0, $result->getDataAsArray()); - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * Comprobar la limpieza el registro de eventos - * - * @throws ConstraintException - * @throws QueryException - */ - public function testClear() - { - self::$repository->clear(); - - $this->assertEquals(0, self::getRowCount('EventLog')); - } - - /** - * Comprobar la creación de eventos - * - * @throws ConstraintException - * @throws QueryException - */ - public function testCreate() - { - $eventlogData = new EventlogData(); - $eventlogData->setAction('test'); - $eventlogData->setLevel('INFO'); - $eventlogData->setUserId(1); - $eventlogData->setLogin('Admin'); - $eventlogData->setIpAddress('127.0.0.1'); - $eventlogData->setDescription('Prueba'); - - $countBefore = self::getRowCount('EventLog'); - - self::$repository->create($eventlogData); - - $countAfter = self::getRowCount('EventLog'); - - $this->assertEquals($countBefore + 1, $countAfter); - - $this->expectException(ConstraintException::class); - - self::$repository->create(new EventlogData()); - } -} diff --git a/tests/SPT/Repositories/ItemPresetRepositoryTest.php b/tests/SPT/Repositories/ItemPresetRepositoryTest.php deleted file mode 100644 index ed4a2dac..00000000 --- a/tests/SPT/Repositories/ItemPresetRepositoryTest.php +++ /dev/null @@ -1,430 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemSearchData; -use SP\Domain\Account\Models\ItemPreset; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\ItemPreset\Ports\ItemPresetRepositoryInterface; -use SP\Infrastructure\ItemPreset\Repositories\ItemPresetRepository; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class ItemPresetRepositoryTest - * - * @package SPT\Repositories - */ -class ItemPresetRepositoryTest extends DatabaseTestCase -{ - /** - * @var ItemPresetRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(ItemPresetRepository::class); - } - - public static function userDataProvider(): array - { - return [ - [1, 1, 1, 3], - [1, 2, 2, 1], - [1, 1, 3, 2], - [2, 2, 2, 2], - [2, 2, 3, 2], - [2, 1, 3, 2], - [3, 1, 1, 3], - [3, 1, 2, 2], - ]; - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(3, self::$repository->deleteByIdBatch([1, 2, 3, 10])); - - $this->assertEquals(2, self::getRowCount('ItemPreset')); - - $this->assertEquals(0, self::$repository->deleteByIdBatch([])); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDelete() - { - $this->assertEquals(1, self::$repository->delete(3)); - - $this->assertEquals(1, self::$repository->delete(4)); - - $this->assertEquals(0, self::$repository->delete(10)); - - $this->assertEquals(3, self::getRowCount('ItemPreset')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch() - { - $this->assertCount(3, self::$repository->getByIdBatch([1, 2, 3])->getDataAsArray()); - $this->assertCount(3, self::$repository->getByIdBatch([1, 2, 5, 10])->getDataAsArray()); - $this->assertCount(0, self::$repository->getByIdBatch([])->getDataAsArray()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdate() - { - $data = new ItemPreset(); - $data->id = 1; - $data->userGroupId = 1; - $data->fixed = 1; - $data->priority = 1; - $data->data = 'data'; - $data->type = 'permission'; - - self::$repository->update($data); - - $this->assertEquals($data, self::$repository->getById(1)->getData()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdateDuplicatedHash() - { - $this->expectException(ConstraintException::class); - - $data = new ItemPreset(); - $data->id = 1; - $data->userGroupId = 1; - $data->fixed = 1; - $data->priority = 10; - $data->data = 'data'; - $data->type = 'permission'; - - self::$repository->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdateUnknownUserId() - { - $this->expectException(ConstraintException::class); - - $data = new ItemPreset(); - $data->id = 2; - $data->userId = 10; - $data->fixed = 1; - $data->priority = 1; - $data->data = 'data'; - $data->type = 'permission'; - - self::$repository->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdateUnknownUserGroupId() - { - $this->expectException(ConstraintException::class); - - $data = new ItemPreset(); - $data->id = 2; - $data->userGroupId = 10; - $data->fixed = 1; - $data->priority = 1; - $data->data = 'data'; - $data->type = 'permission'; - - self::$repository->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdateUnknownUserProfileId() - { - $this->expectException(ConstraintException::class); - - $data = new ItemPreset(); - $data->id = 2; - $data->userProfileId = 10; - $data->fixed = 1; - $data->priority = 1; - $data->data = 'data'; - $data->type = 'permission'; - - self::$repository->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdateUnknownId() - { - $data = new ItemPreset(); - $data->id = 10; - $data->userGroupId = 1; - $data->fixed = 1; - $data->priority = 1; - $data->data = 'data'; - $data->type = 'permission'; - - self::$repository->update($data); - - $this->assertEquals(0, self::$repository->update($data)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $data = new ItemPreset(); - $data->id = 1; - $data->userId = 1; - $data->fixed = 0; - $data->priority = 0; - $data->type = 'permission'; - - $result = self::$repository->getById(1); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertEquals($data, $result->getData()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $count = self::getRowCount('ItemPreset'); - - $result = self::$repository->getAll(); - $this->assertEquals($count, $result->getNumRows()); - - /** @var ItemPreset[] $data */ - $data = $result->getDataAsArray(); - $this->assertCount($count, $data); - - $this->assertInstanceOf(ItemPreset::class, $data[0]); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals('permission', $data[0]->getType()); - $this->assertEquals(1, $data[0]->getUserId()); - $this->assertNull($data[0]->getUserGroupId()); - $this->assertNull($data[0]->getUserProfileId()); - $this->assertNull($data[0]->getData()); - $this->assertEquals(0, $data[0]->getFixed()); - $this->assertEquals(0, $data[0]->getPriority()); - - $this->assertInstanceOf(ItemPreset::class, $data[1]); - $this->assertEquals(2, $data[1]->getId()); - $this->assertEquals('permission', $data[1]->getType()); - - $this->assertInstanceOf(ItemPreset::class, $data[2]); - $this->assertEquals(3, $data[2]->getId()); - $this->assertEquals('permission', $data[2]->getType()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - // Search for user's name - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('demo'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(4, $data[0]->id); - $this->assertEquals('permission', $data[0]->type); - $this->assertEquals(2, $data[0]->userId); - $this->assertNull($data[0]->userGroupId); - $this->assertNull($data[0]->userProfileId); - $this->assertNull($data[0]->data); - $this->assertEquals(0, $data[0]->fixed); - $this->assertEquals(0, $data[0]->priority); - $this->assertEquals('sysPass demo', $data[0]->userName); - - // Search for group's name - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('admins'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(2, $data[0]->id); - $this->assertEquals('permission', $data[0]->type); - $this->assertNull($data[0]->userId); - $this->assertEquals(1, $data[0]->userGroupId); - $this->assertNull($data[0]->userProfileId); - $this->assertNull($data[0]->data); - $this->assertEquals(0, $data[0]->fixed); - $this->assertEquals(10, $data[0]->priority); - $this->assertEquals('Admins', $data[0]->userGroupName); - - // Search for profile's name - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Usuarios'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(5, $data[0]->id); - $this->assertEquals('permission', $data[0]->type); - $this->assertNull($data[0]->userId); - $this->assertNull($data[0]->userGroupId); - $this->assertEquals(3, $data[0]->userProfileId); - $this->assertNull($data[0]->data); - $this->assertEquals(0, $data[0]->fixed); - $this->assertEquals(10, $data[0]->priority); - $this->assertEquals('Usuarios', $data[0]->userProfileName); - - // Search for no results - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('test_permission'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCreate() - { - $data = new ItemPreset(); - $data->id = 6; - $data->userGroupId = 1; - $data->fixed = 1; - $data->priority = 20; - $data->data = 'data'; - $data->type = 'permission'; - - $id = self::$repository->create($data); - - $this->assertEquals($data->id, $id); - $this->assertEquals($data, self::$repository->getById($id)->getData()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCreateDuplicatedHash() - { - $this->expectException(ConstraintException::class); - - $data = new ItemPreset(); - $data->userGroupId = 1; - $data->fixed = 1; - $data->priority = 10; - $data->data = 'data'; - $data->type = 'permission'; - - self::$repository->create($data); - } - - /** - * @dataProvider userDataProvider - * - * @param int $userId - * @param int $userGroupId - * @param int $userProfileId - * @param int $expected - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByFilter($userId, $userGroupId, $userProfileId, $expected) - { - $result = self::$repository->getByFilter('permission', $userId, $userGroupId, $userProfileId); - - $this->assertEquals(1, $result->getNumRows()); - - /** @var ItemPreset $data */ - $data = $result->getData(); - - $this->assertInstanceOf(ItemPreset::class, $data); - $this->assertEquals($expected, $data->getId()); - } -} diff --git a/tests/SPT/Repositories/NotificationRepositoryTest.php b/tests/SPT/Repositories/NotificationRepositoryTest.php deleted file mode 100644 index 203ded56..00000000 --- a/tests/SPT/Repositories/NotificationRepositoryTest.php +++ /dev/null @@ -1,546 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Core\Messages\NotificationMessage; -use SP\DataModel\ItemSearchData; -use SP\DataModel\NotificationData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Notification\Ports\NotificationRepositoryInterface; -use SP\Infrastructure\Notification\Repositories\NotificationRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class NotificationRepositoryTest - * - * @package SPT\Repositories - */ -class NotificationRepositoryTest extends DatabaseTestCase -{ - /** - * @var NotificationRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(NotificationRepository::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteAdmin() - { - $countBefore = self::getRowCount('Notification'); - - $this->assertEquals(1, self::$repository->deleteAdmin(3)); - $this->assertEquals($countBefore - 1, self::getRowCount('Notification')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteAdminBatch() - { - $this->assertEquals(3, self::$repository->deleteAdminBatch([1, 2, 3, 5])); - $this->assertEquals(0, self::getRowCount('Notification')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch() - { - $this->assertEquals(0, self::$repository->getByIdBatch([])->getNumRows()); - - $result = self::$repository->getByIdBatch([1, 2, 3, 4]); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertCount(3, $data); - $this->assertInstanceOf(NotificationData::class, $data[0]); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals('Prueba', $data[0]->getType()); - $this->assertEquals('Accounts', $data[0]->getComponent()); - $this->assertEquals('Notificación de prueba', trim($data[0]->getDescription())); - $this->assertEquals(1529145158, $data[0]->getDate()); - $this->assertEquals(0, $data[0]->isChecked()); - $this->assertEquals(0, $data[0]->isOnlyAdmin()); - $this->assertEquals(0, $data[0]->isSticky()); - $this->assertEquals(2, $data[0]->getUserId()); - - $this->assertEquals(2, $data[1]->getId()); - $this->assertEquals(3, $data[2]->getId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $result = self::$repository->getById(3); - /** @var NotificationData $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(NotificationData::class, $data); - $this->assertEquals(3, $data->getId()); - - $result = self::$repository->getById(4); - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCreate() - { - $data = new NotificationData(); - $data->setId(4); - $data->setUserId(2); - $data->setType('Test'); - $data->setComponent('Config'); - $data->setDescription(NotificationMessage::factory()->setTitle('Prueba')->setDescription(['blablabla'])); - $data->setChecked(0); - $data->setOnlyAdmin(1); - $data->setSticky(1); - - $this->assertEquals(4, self::$repository->create($data)->getLastId()); - - /** @var NotificationData $resultData */ - $resultData = self::$repository->getById(4)->getData(); - - $this->assertEquals($data->getId(), $resultData->getId()); - $this->assertEquals($data->getUserId(), $resultData->getUserId()); - $this->assertEquals($data->getType(), $resultData->getType()); - $this->assertEquals($data->getComponent(), $resultData->getComponent()); - $this->assertEquals($data->isChecked(), $resultData->isChecked()); - $this->assertEquals($data->isOnlyAdmin(), $resultData->isOnlyAdmin()); - $this->assertEquals($data->isSticky(), $resultData->isSticky()); - $this->assertGreaterThan(0, $resultData->getDate()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Test'); - - $result = self::$repository->search($itemSearchData); - - $this->assertEquals(2, $result->getNumRows()); - - $itemSearchData->setSeachString('Global'); - - $result = self::$repository->search($itemSearchData); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(NotificationData::class, $data[0]); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals('Global', $data[0]->getType()); - - $itemSearchData->setSeachString('Accounts'); - - $result = self::$repository->search($itemSearchData); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(3, $result->getNumRows()); - $this->assertCount(3, $data); - $this->assertEquals(1529145313, $data[0]->getDate()); - $this->assertEquals('Accounts', $data[0]->getComponent()); - $this->assertEquals(1529145296, $data[1]->getDate()); - $this->assertEquals('Accounts', $data[1]->getComponent()); - $this->assertEquals(1529145158, $data[2]->getDate()); - $this->assertEquals('Accounts', $data[2]->getComponent()); - - $itemSearchData->setSeachString(null); - - $result = self::$repository->search($itemSearchData); - - $this->assertEquals(3, $result->getNumRows()); - $this->assertCount(3, $result->getDataAsArray()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSetCheckedById() - { - $this->assertEquals(1, self::$repository->setCheckedById(1)); - $this->assertEquals(0, self::$repository->setCheckedById(4)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdate() - { - $data = new NotificationData(); - $data->setId(3); - $data->setUserId(2); - $data->setType('Test'); - $data->setComponent('Config'); - $data->setDescription(NotificationMessage::factory()->setTitle('Prueba')->setDescription(['blablabla'])); - $data->setChecked(0); - $data->setOnlyAdmin(1); - $data->setSticky(1); - - $this->assertEquals(1, self::$repository->update($data)); - - /** @var NotificationData $resultData */ - $resultData = self::$repository->getById($data->getId())->getData(); - - $this->assertEquals($data->getId(), $resultData->getId()); - $this->assertEquals($data->getUserId(), $resultData->getUserId()); - $this->assertEquals($data->getType(), $resultData->getType()); - $this->assertEquals($data->getComponent(), $resultData->getComponent()); - $this->assertEquals($data->isChecked(), $resultData->isChecked()); - $this->assertEquals($data->isOnlyAdmin(), $resultData->isOnlyAdmin()); - $this->assertEquals($data->isSticky(), $resultData->isSticky()); - $this->assertGreaterThan(0, $resultData->getDate()); - - $data->setId(4); - - $this->assertEquals(0, self::$repository->update($data)); - - // FIXME: No exception on Travis CI?? -// $data = new NotificationData(); -// $data->setId(1); -// -// $this->expectException(ConstraintException::class); -// -// self::$repository->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearchForUserId() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Test'); - - $result = self::$repository->searchForUserId($itemSearchData, 2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertEquals(2, $data[0]->getId()); - - $itemSearchData->setSeachString('Accounts'); - - $result = self::$repository->searchForUserId($itemSearchData, 2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals(1, $data[1]->getId()); - - $itemSearchData->setSeachString('Admins'); - - $result = self::$repository->searchForUserId($itemSearchData, 2); - - $this->assertEquals(0, $result->getNumRows()); - - $itemSearchData->setSeachString('Global'); - - $result = self::$repository->searchForUserId($itemSearchData, 2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertEquals(2, $data[0]->getId()); - - $itemSearchData->setSeachString(''); - - $result = self::$repository->searchForUserId($itemSearchData, 2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals(1, $data[1]->getId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $result = self::$repository->getAll(); - - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(3, $result->getNumRows()); - $this->assertCount(3, $data); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals(2, $data[1]->getId()); - $this->assertEquals(3, $data[2]->getId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetForUserIdByDate() - { - // Forces an update of the notification's date field - $this->assertEquals(1, self::$repository->update(self::$repository->getById(1)->getData())); - - $result = self::$repository->getForUserIdByDate('Accounts', 2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertEquals(1, $data[0]->getId()); - - $result = self::$repository->getForUserIdByDate('Accounts', 3); - - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDelete() - { - $this->assertEquals(1, self::$repository->delete(3)); - $this->assertEquals(0, self::$repository->delete(4)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllForUserId() - { - $result = self::$repository->getAllForUserId(2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals(1, $data[1]->getId()); - - $result = self::$repository->getAllForUserId(3); - - $this->assertEquals(1, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(2, self::$repository->deleteByIdBatch([1, 2, 3, 4])); - $this->assertEquals(0, self::$repository->deleteByIdBatch([])); - - $this->assertEquals(1, self::getRowCount('Notification')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllActiveForUserId() - { - $result = self::$repository->getAllActiveForUserId(2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals(1, $data[1]->getId()); - - $result = self::$repository->getAllActiveForUserId(3); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertEquals(2, $data[0]->getId()); - - self::$repository->setCheckedById(1); - - $result = self::$repository->getAllActiveForUserId(2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertEquals(2, $data[0]->getId()); - - self::$repository->setCheckedById(2); - - $this->assertEquals(0, self::$repository->getAllActiveForUserId(2)->getNumRows()); - $this->assertEquals(0, self::$repository->getAllActiveForUserId(3)->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllActiveForAdmin() - { - $result = self::$repository->getAllActiveForAdmin(1); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertEquals(3, $data[0]->getId()); - $this->assertEquals(2, $data[1]->getId()); - - $result = self::$repository->getAllActiveForAdmin(2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(3, $result->getNumRows()); - $this->assertCount(3, $data); - $this->assertEquals(3, $data[0]->getId()); - $this->assertEquals(2, $data[1]->getId()); - $this->assertEquals(1, $data[2]->getId()); - - $result = self::$repository->getAllActiveForAdmin(3); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertEquals(3, $data[0]->getId()); - $this->assertEquals(2, $data[1]->getId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearchForAdmin() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Test'); - - $result = self::$repository->searchForAdmin($itemSearchData, 1); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertEquals(3, $data[0]->getId()); - $this->assertEquals(2, $data[1]->getId()); - - $itemSearchData->setSeachString('Accounts'); - - $result = self::$repository->searchForAdmin($itemSearchData, 2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(3, $result->getNumRows()); - $this->assertCount(3, $data); - $this->assertEquals(3, $data[0]->getId()); - $this->assertEquals(2, $data[1]->getId()); - $this->assertEquals(1, $data[2]->getId()); - - $itemSearchData->setSeachString('Admins'); - - $result = self::$repository->searchForAdmin($itemSearchData, 2); - - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertEquals(3, $data[0]->getId()); - - $itemSearchData->setSeachString('Global'); - - $result = self::$repository->searchForAdmin($itemSearchData, 2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertEquals(2, $data[0]->getId()); - - $itemSearchData->setSeachString(''); - - $result = self::$repository->searchForAdmin($itemSearchData, 2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(3, $result->getNumRows()); - $this->assertCount(3, $data); - $this->assertEquals(3, $data[0]->getId()); - $this->assertEquals(2, $data[1]->getId()); - $this->assertEquals(1, $data[2]->getId()); - } -} diff --git a/tests/SPT/Repositories/PluginDataRepositoryTest.php b/tests/SPT/Repositories/PluginDataRepositoryTest.php deleted file mode 100644 index a44cca32..00000000 --- a/tests/SPT/Repositories/PluginDataRepositoryTest.php +++ /dev/null @@ -1,305 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\NoSuchPropertyException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\Plugin\Ports\PluginDataRepositoryInterface; -use SP\Infrastructure\Plugin\Repositories\PluginDataModel; -use SP\Infrastructure\Plugin\Repositories\PluginDataRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class PluginDataRepositoryTest - * - * @package SPT\Repositories - */ -class PluginDataRepositoryTest extends DatabaseTestCase -{ - /** - * @var PluginDataRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(PluginDataRepository::class); - } - - /** - * @throws ConstraintException - * @throws CryptoException - * @throws NoSuchPropertyException - * @throws QueryException - */ - public function testUpdate() - { - $data = new PluginDataModel(); - $data->setItemId(1); - $data->setName('Authenticator'); - $data->setData('data_updated'); - - $data->encrypt('12345678900'); - - $this->assertEquals(1, self::$repository->update($data)); - - $result = self::$repository->getByItemId($data->getName(), $data->getItemId()); - - $this->assertEquals(1, $result->getNumRows()); - - /** @var PluginDataModel $itemData */ - $itemData = $result->getData(); - - $this->assertEquals($data->getData(), $itemData->getData()); - - $data = new PluginDataModel(); - $data->setItemId(0); - $data->setName('Authenticator'); - $data->setData('data_updated'); - - $data->encrypt('test'); - - $this->assertEquals(0, self::$repository->update($data)); - } - - /** - * @throws ConstraintException - * @throws CryptoException - * @throws NoSuchPropertyException - * @throws QueryException - */ - public function testUpdateUnkown() - { - $data = new PluginDataModel(); - $data->setItemId(2); - $data->setName('Test'); - $data->setData('data'); - - $data->encrypt('test'); - - $this->assertEquals(0, self::$repository->update($data)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $result = self::$repository->getAll(); - /** @var PluginDataModel[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(4, $result->getNumRows()); - $this->assertCount(4, $data); - $this->assertEquals(1, $data[0]->getItemId()); - $this->assertEquals('Authenticator', $data[0]->getName()); - $this->assertNotEmpty($data[0]->getData()); - $this->assertNotEmpty($data[0]->getKey()); - - $this->assertEquals(2, $data[1]->getItemId()); - $this->assertEquals(3, $data[2]->getItemId()); - $this->assertEquals(2, $data[3]->getItemId()); - } - - /** - * @requires testGetById - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDelete() - { - $this->assertEquals(2, self::$repository->delete('Authenticator')); - $this->assertEquals(0, self::$repository->getById('Authenticator')->getNumRows()); - - $this->assertEquals(1, self::$repository->delete('DokuWiki')); - $this->assertEquals(0, self::$repository->getById('DokuWiki')->getNumRows()); - - $this->assertEquals(0, self::$repository->delete('Test')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByItemId() - { - $this->assertEquals(1, self::$repository->deleteByItemId('Authenticator', 1)); - $this->assertEquals(1, self::$repository->getById('Authenticator')->getNumRows()); - - $this->assertEquals(0, self::$repository->delete('Test')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $result = self::$repository->getById('Authenticator'); - /** @var PluginDataModel[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertInstanceOf(PluginDataModel::class, $data[0]); - $this->assertEquals(1, $data[0]->getItemId()); - $this->assertEquals('Authenticator', $data[0]->getName()); - $this->assertNotEmpty($data[0]->getData()); - $this->assertNotEmpty($data[0]->getKey()); - - $this->assertInstanceOf(PluginDataModel::class, $data[1]); - $this->assertEquals(2, $data[1]->getItemId()); - $this->assertEquals('Authenticator', $data[1]->getName()); - $this->assertNotEmpty($data[1]->getData()); - $this->assertNotEmpty($data[1]->getKey()); - - $this->assertEquals(1, self::$repository->getById('XML Exporter')->getNumRows()); - - $this->assertEquals(0, self::$repository->getById('Test')->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByItemId() - { - $result = self::$repository->getByItemId('Authenticator', 1); - /** @var PluginDataModel $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(PluginDataModel::class, $data); - $this->assertEquals(1, $data->getItemId()); - $this->assertEquals('Authenticator', $data->getName()); - $this->assertNotEmpty($data->getData()); - $this->assertNotEmpty($data->getKey()); - - $this->assertEquals(0, self::$repository->getByItemId('Test', 1)->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(3, self::$repository->deleteByIdBatch(['Authenticator', 'XML Exporter', 'Test'])); - $this->assertEquals(0, self::$repository->deleteByIdBatch([])); - } - - /** - * @throws ConstraintException - * @throws CryptoException - * @throws NoSuchPropertyException - * @throws QueryException - */ - public function testCreate() - { - $data = new PluginDataModel(); - $data->setItemId(4); - $data->setName('Authenticator'); - $data->setData('data'); - - $data->encrypt('12345678900'); - - self::$repository->create($data); - - $result = self::$repository->getByItemId($data->getName(), $data->getItemId()); - - $this->assertEquals(1, $result->getNumRows()); - - /** @var PluginDataModel $itemData */ - $itemData = $result->getData(); - - $this->assertEquals($data->getName(), $itemData->getName()); - $this->assertEquals($data->getData(), $itemData->getData()); - - $this->expectException(ConstraintException::class); - - self::$repository->create($data); - } - - /** - * @throws ConstraintException - * @throws CryptoException - * @throws NoSuchPropertyException - * @throws QueryException - */ - public function testCreateUnknown() - { - $this->expectException(ConstraintException::class); - - $data = new PluginDataModel(); - $data->setItemId(4); - $data->setName('Test'); - $data->setData('data'); - - $data->encrypt('test'); - - self::$repository->create($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch() - { - $result = self::$repository->getByIdBatch(['Authenticator', 'XML Exporter', 'Test']); - /** @var PluginDataModel[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(3, $result->getNumRows()); - $this->assertCount(3, $data); - $this->assertEquals(1, $data[0]->getItemId()); - $this->assertEquals(2, $data[1]->getItemId()); - $this->assertEquals(2, $data[2]->getItemId()); - - $result = self::$repository->getByIdBatch([]); - - $this->assertEquals(0, $result->getNumRows()); - } -} diff --git a/tests/SPT/Repositories/PluginRepositoryTest.php b/tests/SPT/Repositories/PluginRepositoryTest.php deleted file mode 100644 index 2614a3d3..00000000 --- a/tests/SPT/Repositories/PluginRepositoryTest.php +++ /dev/null @@ -1,373 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemData; -use SP\DataModel\ItemSearchData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\Plugin\Ports\PluginRepositoryInterface; -use SP\Infrastructure\Plugin\Repositories\PluginModel; -use SP\Infrastructure\Plugin\Repositories\PluginRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class PluginRepositoryTest - * - * @package SPT\Repositories - */ -class PluginRepositoryTest extends DatabaseTestCase -{ - /** - * @var PluginRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(PluginRepository::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdate() - { - $data = new PluginModel(); - $data->setId(1); - $data->setName('Authenticator 2'); - $data->setAvailable(1); - $data->setEnabled(1); - $data->setData('data'); - - $this->assertEquals(1, self::$repository->update($data)); - - $result = self::$repository->getById(1); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertEquals($data, $result->getData()); - - $data->setId(null); - $data->setName('Authenticator'); - - $this->assertEquals(0, self::$repository->update($data)); - - $data->setId(2); - $data->setName('DokuWiki'); - - $this->expectException(ConstraintException::class); - - self::$repository->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $result = self::$repository->getAll(); - /** @var PluginModel[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(3, $result->getNumRows()); - $this->assertCount(3, $data); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals('Authenticator', $data[0]->getName()); - $this->assertNull($data[0]->getData()); - $this->assertEquals(1, $data[0]->getAvailable()); - $this->assertEquals(0, $data[0]->getEnabled()); - - $this->assertEquals(3, $data[1]->getId()); - $this->assertEquals(2, $data[2]->getId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByName() - { - $result = self::$repository->getByName('Authenticator'); - /** @var PluginModel $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(PluginModel::class, $data); - $this->assertEquals(1, $data->getId()); - $this->assertEquals('Authenticator', $data->getName()); - $this->assertNull($data->getData()); - $this->assertEquals(1, $data->getAvailable()); - $this->assertEquals(0, $data->getEnabled()); - - $this->assertEquals(0, self::$repository->getByName('Authenticator 2')->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testToggleAvailableByName() - { - $this->assertEquals(1, self::$repository->toggleAvailableByName('Authenticator', 0)); - - /** @var PluginModel $data */ - $data = self::$repository->getByName('Authenticator')->getData(); - - $this->assertEquals(0, $data->getAvailable()); - - $this->assertEquals(0, self::$repository->toggleAvailableByName('Authenticator 2', 1)); - } - - /** - * @requires testGetById - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDelete() - { - $this->assertEquals(1, self::$repository->delete(1)); - $this->assertEquals(0, self::$repository->getById(1)->getNumRows()); - - $this->assertEquals(0, self::$repository->delete(4)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testToggleEnabled() - { - $this->assertEquals(1, self::$repository->toggleEnabled(1, 1)); - $this->assertEquals(0, self::$repository->toggleEnabled(4, 0)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $result = self::$repository->getById(1); - /** @var PluginModel $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(PluginModel::class, $data); - $this->assertEquals(1, $data->getId()); - $this->assertEquals('Authenticator', $data->getName()); - $this->assertNull($data->getData()); - $this->assertEquals(1, $data->getAvailable()); - $this->assertEquals(0, $data->getEnabled()); - - $this->assertEquals(0, self::$repository->getById(4)->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(2, self::$repository->deleteByIdBatch([1, 2, 4])); - $this->assertEquals(0, self::$repository->deleteByIdBatch([])); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetEnabled() - { - $result = self::$repository->getEnabled(); - /** @var ItemData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertInstanceOf(ItemData::class, $data[0]); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals('XML Exporter', $data[0]->getName()); - $this->assertInstanceOf(ItemData::class, $data[1]); - $this->assertEquals(3, $data[1]->getId()); - $this->assertEquals('DokuWiki', $data[1]->getName()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCreate() - { - $data = new PluginModel(); - $data->setId(4); - $data->setName('Authenticator 2'); - $data->setAvailable(1); - $data->setEnabled(1); - $data->setData('data'); - - $this->assertEquals(4, self::$repository->create($data)->getLastId()); - - $result = self::$repository->getById(4); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertEquals($data, $result->getData()); - - - $this->expectException(ConstraintException::class); - - self::$repository->create($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCreateBlank() - { - $this->expectException(ConstraintException::class); - - self::$repository->create(new PluginModel()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testResetById() - { - $this->assertEquals(1, self::$repository->resetById(2)); - - /** @var PluginModel $data */ - $data = self::$repository->getById(2)->getData(); - - $this->assertNull($data->getData()); - - $this->assertEquals(0, self::$repository->resetById(4)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Auth'); - - $result = self::$repository->search($itemSearchData); - /** @var PluginModel[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals('Authenticator', $data[0]->getName()); - $this->assertEquals(0, $data[0]->getEnabled()); - $this->assertEquals(1, $data[0]->getAvailable()); - - $itemSearchData->setSeachString('test'); - - $result = self::$repository->search($itemSearchData); - $this->assertEquals(0, $result->getNumRows()); - - $itemSearchData->setSeachString(''); - - $result = self::$repository->search($itemSearchData); - $this->assertEquals(3, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testToggleEnabledByName() - { - $this->assertEquals(1, self::$repository->toggleEnabledByName('Authenticator', 1)); - - /** @var PluginModel $data */ - $data = self::$repository->getByName('Authenticator')->getData(); - - $this->assertEquals(1, $data->getEnabled()); - - $this->assertEquals(0, self::$repository->toggleEnabledByName('Test', 0)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testToggleAvailable() - { - $this->assertEquals(1, self::$repository->toggleAvailable(1, 0)); - - /** @var PluginModel $data */ - $data = self::$repository->getByName('Authenticator')->getData(); - - $this->assertEquals(0, $data->getAvailable()); - - $this->assertEquals(0, self::$repository->toggleAvailable(4, 1)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch() - { - $result = self::$repository->getByIdBatch([1, 2, 4]); - /** @var PluginModel[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals(2, $data[1]->getId()); - - $result = self::$repository->getByIdBatch([]); - - $this->assertEquals(0, $result->getNumRows()); - } -} diff --git a/tests/SPT/Repositories/PublicLinkRepositoryTest.php b/tests/SPT/Repositories/PublicLinkRepositoryTest.php deleted file mode 100644 index 621cb833..00000000 --- a/tests/SPT/Repositories/PublicLinkRepositoryTest.php +++ /dev/null @@ -1,471 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use Defuse\Crypto\Exception\EnvironmentIsBrokenException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemSearchData; -use SP\DataModel\PublicLinkData; -use SP\DataModel\PublicLinkListData; -use SP\Domain\Account\Ports\PublicLinkRepositoryInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Infrastructure\Account\Repositories\PublicLinkRepository; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Util\PasswordUtil; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class PublicLinkRepositoryTest - * - * @package SPT\Repositories - */ -class PublicLinkRepositoryTest extends DatabaseTestCase -{ - /** - * @var PublicLinkRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(PublicLinkRepository::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetHashForItem() - { - $result = self::$repository->getHashForItem(2); - /** @var PublicLinkData $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertEquals(3, $data->getId()); - $this->assertEquals(1, $data->getUserId()); - $this->assertEquals(pack('H*', '616337343462363934383832336362303531343534366335363739383163653466653732343064663339363832366439396632346664396131333434'), $data->getHash()); - - $result = self::$repository->getHashForItem(3); - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Google'); - - $result = self::$repository->search($itemSearchData); - /** @var PublicLinkListData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(PublicLinkListData::class, $data[0]); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals(1, $data[0]->getItemId()); - $this->assertEquals(pack('H*', '636564333430306561313730363139616437643235383934383862366236303734376561393966313265323230663561393130656465366438333466'), $data[0]->getHash()); - $this->assertNotEmpty($data[0]->getData()); - $this->assertEquals(1, $data[0]->getUserId()); - $this->assertEquals(1, $data[0]->getTypeId()); - $this->assertEquals(0, $data[0]->isNotify()); - $this->assertEquals(1529228863, $data[0]->getDateAdd()); - $this->assertEquals(1532280825, $data[0]->getDateExpire()); - $this->assertEquals(0, $data[0]->getDateUpdate()); - $this->assertEquals(0, $data[0]->getCountViews()); - $this->assertEquals(3, $data[0]->getMaxCountViews()); - $this->assertEquals(0, $data[0]->getTotalCountViews()); - $this->assertNull($data[0]->getUseInfo()); - $this->assertEquals('Google', $data[0]->getAccountName()); - $this->assertEquals('admin', $data[0]->getUserLogin()); - - $itemSearchData->setSeachString('Apple'); - - $result = self::$repository->search($itemSearchData); - /** @var PublicLinkListData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(PublicLinkListData::class, $data[0]); - $this->assertEquals(3, $data[0]->getId()); - $this->assertEquals(2, $data[0]->getItemId()); - - $itemSearchData->setSeachString(''); - - $result = self::$repository->search($itemSearchData); - - $this->assertEquals(2, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(2, self::$repository->deleteByIdBatch([1, 2, 3])); - $this->assertEquals(0, self::$repository->deleteByIdBatch([])); - - $this->assertEquals(0, self::getRowCount('PublicLink')); - } - - /** - * @throws EnvironmentIsBrokenException - * @throws ConstraintException - * @throws QueryException - * @throws DuplicatedItemException - * @throws SPException - */ - public function testCreate() - { - self::$repository->delete(2); - - $data = new PublicLinkData(); - $data->setItemId(1); - $data->setHash(PasswordUtil::generateRandomBytes()); - $data->setData('data'); - $data->setUserId(1); - $data->setTypeId(1); - $data->setNotify(1); - $data->setDateExpire(time() + 600); - $data->setDateAdd(time()); - $data->setMaxCountViews(3); - - $this->assertEquals(4, self::$repository->create($data)->getLastId()); - - /** @var PublicLinkListData $resultData */ - $resultData = self::$repository->getById(4)->getData(); - - $this->assertEquals(4, $resultData->getId()); - $this->assertEquals($data->getItemId(), $resultData->getItemId()); - $this->assertEquals($data->getHash(), $resultData->getHash()); - $this->assertEquals($data->getData(), $resultData->getData()); - $this->assertEquals($data->getUserId(), $resultData->getUserId()); - $this->assertEquals($data->getTypeId(), $resultData->getTypeId()); - $this->assertEquals($data->isNotify(), $resultData->isNotify()); - $this->assertEquals($data->getDateExpire(), $resultData->getDateExpire()); - $this->assertTrue($data->getDateAdd() <= $resultData->getDateAdd()); - $this->assertEquals($data->getMaxCountViews(), $resultData->getMaxCountViews()); - - $this->expectException(DuplicatedItemException::class); - - self::$repository->create($data); - - $this->expectException(ConstraintException::class); - - $data->setItemId(10); - - self::$repository->create($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $result = self::$repository->getById(2); - /** @var PublicLinkListData $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(PublicLinkListData::class, $data); - $this->assertEquals(2, $data->getId()); - $this->assertEquals(1, $data->getItemId()); - $this->assertEquals(pack('H*', '636564333430306561313730363139616437643235383934383862366236303734376561393966313265323230663561393130656465366438333466'), $data->getHash()); - $this->assertNotEmpty($data->getData()); - $this->assertEquals(1, $data->getUserId()); - $this->assertEquals(1, $data->getTypeId()); - $this->assertEquals(0, $data->isNotify()); - $this->assertEquals(1529228863, $data->getDateAdd()); - $this->assertEquals(1532280825, $data->getDateExpire()); - $this->assertEquals(0, $data->getDateUpdate()); - $this->assertEquals(0, $data->getCountViews()); - $this->assertEquals(3, $data->getMaxCountViews()); - $this->assertEquals(0, $data->getTotalCountViews()); - $this->assertNull($data->getUseInfo()); - $this->assertEquals('Google', $data->getAccountName()); - $this->assertEquals('admin', $data->getUserLogin()); - - $this->assertEquals(0, self::$repository->getById(10)->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDelete() - { - $this->assertEquals(1, self::$repository->delete(2)); - $this->assertEquals(1, self::$repository->delete(3)); - $this->assertEquals(0, self::$repository->delete(4)); - - $this->assertEquals(0, self::getRowCount('PublicLink')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testAddLinkView() - { - $hash = pack('H*', '636564333430306561313730363139616437643235383934383862366236303734376561393966313265323230663561393130656465366438333466'); - - $useInfo = [ - 'who' => SELF_IP_ADDRESS, - 'time' => time(), - 'hash' => $hash, - 'agent' => 'Mozilla/Firefox', - 'https' => true - ]; - - $data = new PublicLinkData(); - $data->setHash($hash); - $data->setUseInfo($useInfo); - - $this->assertEquals(1, self::$repository->addLinkView($data)); - - /** @var PublicLinkData $resultData */ - $resultData = self::$repository->getByHash($hash)->getData(); - - $this->assertEquals(1, $resultData->getCountViews()); - $this->assertEquals(1, $resultData->getTotalCountViews()); - $this->assertEquals($data->getUseInfo(), $resultData->getUseInfo()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByHash() - { - $hash = pack('H*', '636564333430306561313730363139616437643235383934383862366236303734376561393966313265323230663561393130656465366438333466'); - - $result = self::$repository->getByHash($hash); - /** @var PublicLinkData $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(PublicLinkData::class, $data); - $this->assertEquals(2, $data->getId()); - $this->assertEquals(1, $data->getItemId()); - $this->assertEquals($hash, $data->getHash()); - $this->assertNotEmpty($data->getData()); - $this->assertEquals(1, $data->getUserId()); - $this->assertEquals(1, $data->getTypeId()); - $this->assertEquals(0, $data->isNotify()); - $this->assertEquals(1529228863, $data->getDateAdd()); - $this->assertEquals(1532280825, $data->getDateExpire()); - $this->assertEquals(0, $data->getDateUpdate()); - $this->assertEquals(0, $data->getCountViews()); - $this->assertEquals(3, $data->getMaxCountViews()); - $this->assertEquals(0, $data->getTotalCountViews()); - $this->assertNull($data->getUseInfo()); - - $this->assertEquals(0, self::$repository->getByHash('')->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - * @throws EnvironmentIsBrokenException - */ - public function testRefresh() - { - $data = new PublicLinkData(); - $data->setHash(PasswordUtil::generateRandomBytes()); - $data->setDateExpire(time() + 3600); - $data->setMaxCountViews(6); - $data->setData('data_new'); - $data->setId(2); - - $this->assertEquals(1, self::$repository->refresh($data)); - - /** @var PublicLinkListData $resultData */ - $resultData = self::$repository->getById(2)->getData(); - - $this->assertEquals($data->getHash(), $resultData->getHash()); - $this->assertEquals($data->getDateExpire(), $resultData->getDateExpire()); - $this->assertEquals($data->getMaxCountViews(), $resultData->getMaxCountViews()); - $this->assertEquals($data->getData(), $resultData->getData()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testRefreshNullHash() - { - $this->markTestIncomplete('Not working on Travis CI'); - - $data = new PublicLinkData(); - $data->setHash(null); - $data->setDateExpire(time() + 3600); - $data->setMaxCountViews(6); - $data->setData('data_new'); - $data->setId(1); - - $this->expectException(ConstraintException::class); - - self::$repository->refresh($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch() - { - $result = self::$repository->getByIdBatch([1, 2, 3]); - /** @var PublicLinkListData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - - $this->assertInstanceOf(PublicLinkListData::class, $data[0]); - $this->assertEquals(2, $data[0]->getId()); - - $this->assertInstanceOf(PublicLinkListData::class, $data[1]); - $this->assertEquals(3, $data[1]->getId()); - $this->assertEquals(2, $data[1]->getItemId()); - $this->assertEquals(pack('H*', '616337343462363934383832336362303531343534366335363739383163653466653732343064663339363832366439396632346664396131333434'), $data[1]->getHash()); - $this->assertNotEmpty($data[1]->getData()); - $this->assertEquals(1, $data[1]->getUserId()); - $this->assertEquals(1, $data[1]->getTypeId()); - $this->assertEquals(0, $data[1]->isNotify()); - $this->assertEquals(1529276100, $data[1]->getDateAdd()); - $this->assertEquals(1532280828, $data[1]->getDateExpire()); - $this->assertEquals(0, $data[1]->getDateUpdate()); - $this->assertEquals(0, $data[1]->getCountViews()); - $this->assertEquals(3, $data[1]->getMaxCountViews()); - $this->assertEquals(0, $data[1]->getTotalCountViews()); - $this->assertNull($data[1]->getUseInfo()); - $this->assertEquals('Apple', $data[1]->getAccountName()); - $this->assertEquals('admin', $data[1]->getUserLogin()); - - $this->assertEquals(0, self::$repository->getByIdBatch([])->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $result = self::$repository->getAll(); - /** @var PublicLinkListData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - - $this->assertInstanceOf(PublicLinkListData::class, $data[0]); - $this->assertEquals(2, $data[0]->getId()); - - $this->assertInstanceOf(PublicLinkListData::class, $data[1]); - $this->assertEquals(3, $data[1]->getId()); - $this->assertEquals(2, $data[1]->getItemId()); - $this->assertEquals(pack('H*', '616337343462363934383832336362303531343534366335363739383163653466653732343064663339363832366439396632346664396131333434'), $data[1]->getHash()); - $this->assertNotEmpty($data[1]->getData()); - $this->assertEquals(1, $data[1]->getUserId()); - $this->assertEquals(1, $data[1]->getTypeId()); - $this->assertEquals(0, $data[1]->isNotify()); - $this->assertEquals(1529276100, $data[1]->getDateAdd()); - $this->assertEquals(1532280828, $data[1]->getDateExpire()); - $this->assertEquals(0, $data[1]->getDateUpdate()); - $this->assertEquals(0, $data[1]->getCountViews()); - $this->assertEquals(3, $data[1]->getMaxCountViews()); - $this->assertEquals(0, $data[1]->getTotalCountViews()); - $this->assertNull($data[1]->getUseInfo()); - $this->assertEquals('Apple', $data[1]->getAccountName()); - $this->assertEquals('admin', $data[1]->getUserLogin()); - } - - /** - * @throws ConstraintException - * @throws EnvironmentIsBrokenException - * @throws QueryException - * @throws SPException - */ - public function testUpdate() - { - $data = new PublicLinkData(); - $data->setId(2); - $data->setItemId(3); - $data->setHash(PasswordUtil::generateRandomBytes()); - $data->setData('data'); - $data->setUserId(2); - $data->setTypeId(1); - $data->setNotify(0); - $data->setDateExpire(time() + 3600); - $data->setDateAdd(time()); - $data->setMaxCountViews(6); - - $this->assertEquals(1, self::$repository->update($data)); - - /** @var PublicLinkListData $resultData */ - $resultData = self::$repository->getById(2)->getData(); - - $this->assertEquals(2, $resultData->getId()); - $this->assertEquals($data->getItemId(), $resultData->getItemId()); - $this->assertEquals($data->getHash(), $resultData->getHash()); - $this->assertEquals($data->getData(), $resultData->getData()); - $this->assertEquals($data->getUserId(), $resultData->getUserId()); - $this->assertEquals($data->getTypeId(), $resultData->getTypeId()); - $this->assertEquals($data->isNotify(), $resultData->isNotify()); - $this->assertEquals($data->getDateExpire(), $resultData->getDateExpire()); - $this->assertEquals($data->getDateAdd(), $resultData->getDateAdd()); - $this->assertEquals($data->getMaxCountViews(), $resultData->getMaxCountViews()); - - $this->expectException(ConstraintException::class); - - $data->setItemId(2); - - self::$repository->update($data); - } -} diff --git a/tests/SPT/Repositories/TagRepositoryTest.php b/tests/SPT/Repositories/TagRepositoryTest.php deleted file mode 100644 index 1d0f1148..00000000 --- a/tests/SPT/Repositories/TagRepositoryTest.php +++ /dev/null @@ -1,257 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\CategoryData; -use SP\DataModel\ItemSearchData; -use SP\DataModel\TagData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\Tag\Ports\TagRepositoryInterface; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\Tag\Repositories\TagRepository; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class TagRepositoryTest - * - * Tests de integración para comprobar las consultas a la BBDD relativas a las etiquetas - * - * @package SPT - */ -class TagRepositoryTest extends DatabaseTestCase -{ - /** - * @var TagRepositoryInterface - */ - private static $repository; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(TagRepository::class); - } - - /** - * Comprobar la búsqueda mediante texto - * - * @throws QueryException - * @throws ConstraintException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('www'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(1, $data[0]->id); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('prueba'); - - $result = self::$repository->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $result->getDataAsArray()); - } - - /** - * Comprobar los resultados de obtener las etiquetas por Id - * - * @throws QueryException - * @throws ConstraintException - */ - public function testGetById() - { - $this->assertNull(self::$repository->getById(10)->getData()); - - /** @var CategoryData $data */ - $data = self::$repository->getById(1)->getData(); - - $this->assertEquals('www', $data->getName()); - - /** @var CategoryData $data */ - $data = self::$repository->getById(2)->getData(); - - $this->assertEquals('windows', $data->getName()); - } - - /** - * Comprobar la obtención de todas las etiquetas - * - * @throws QueryException - * @throws ConstraintException - */ - public function testGetAll() - { - $count = self::getRowCount('Tag'); - - $results = self::$repository->getAll(); - - $this->assertCount($count, $results); - - $this->assertInstanceOf(TagData::class, $results[0]); - $this->assertEquals('Linux', $results[0]->getName()); - - $this->assertInstanceOf(TagData::class, $results[1]); - $this->assertEquals('windows', $results[1]->getName()); - - $this->assertInstanceOf(TagData::class, $results[2]); - $this->assertEquals('www', $results[2]->getName()); - } - - /** - * Comprobar la actualización de etiquetas - * - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdate() - { - $tagData = new TagData(); - $tagData->id = 1; - $tagData->name = 'Servidor'; - - self::$repository->update($tagData); - - /** @var CategoryData $data */ - $data = self::$repository->getById(1)->getData(); - - $this->assertEquals($data->getName(), $tagData->name); - - // Comprobar la a actualización con un nombre duplicado comprobando su hash - $tagData = new TagData(); - $tagData->id = 1; - $tagData->name = ' linux.'; - - $this->expectException(DuplicatedItemException::class); - - self::$repository->update($tagData); - } - - /** - * Comprobar la eliminación de etiquetas - * - * @throws SPException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(0, self::$repository->deleteByIdBatch([4])); - $this->assertEquals(3, self::$repository->deleteByIdBatch([1, 2, 3])); - - $this->assertEquals(0, self::getRowCount('Tag')); - } - - /** - * Comprobar la creación de etiquetas - * - * @throws DuplicatedItemException - * @throws SPException - */ - public function testCreate() - { - $countBefore = self::getRowCount('Tag'); - - $tagData = new TagData(); - $tagData->name = 'Core'; - - $id = self::$repository->create($tagData); - - // Comprobar que el Id devuelto corresponde con la etiqueta creada - $data = self::$repository->getById($id)->getData(); - - $this->assertEquals($tagData->name, $data->getName()); - - $countAfter = self::getRowCount('Tag'); - - $this->assertEquals($countBefore + 1, $countAfter); - } - - /** - * Comprobar la eliminación de etiquetas por Id - * - * @throws QueryException - * @throws ConstraintException - */ - public function testDelete() - { - $countBefore = self::getRowCount('Tag'); - - $this->assertEquals(1, self::$repository->delete(3)); - - $countAfter = self::getRowCount('Tag'); - - $this->assertEquals($countBefore - 1, $countAfter); - - // Comprobar la eliminación de etiquetas usadas - $this->assertEquals(1, self::$repository->delete(1)); - } - - /** - * Comprobar la obtención de etiquetas por Id en lote - * - * @throws QueryException - * @throws ConstraintException - */ - public function testGetByIdBatch() - { - $this->assertCount(3, self::$repository->getByIdBatch([1, 2, 3])->getDataAsArray()); - $this->assertCount(3, self::$repository->getByIdBatch([1, 2, 3, 4, 5])->getDataAsArray()); - $this->assertCount(0, self::$repository->getByIdBatch([])->getDataAsArray()); - } - - /** - * @throws QueryException - * @throws ConstraintException - */ - public function testCheckInUse() - { - $this->assertTrue(self::$repository->checkInUse(1)); - } -} diff --git a/tests/SPT/Repositories/TrackRepositoryTest.php b/tests/SPT/Repositories/TrackRepositoryTest.php deleted file mode 100644 index 534616fc..00000000 --- a/tests/SPT/Repositories/TrackRepositoryTest.php +++ /dev/null @@ -1,192 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\TrackData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\InvalidArgumentException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Security\Ports\TrackRepositoryInterface; -use SP\Infrastructure\Security\Repositories\TrackRepository; -use SP\Infrastructure\Security\Repositories\TrackRequest; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class TrackRepositoryTest - * - * @package SPT\Repositories - */ -class TrackRepositoryTest extends DatabaseTestCase -{ - /** - * @var TrackRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(TrackRepository::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDelete() - { - $this->assertEquals(1, self::$repository->delete(1)); - - $this->assertEquals(5, self::getRowCount('Track')); - - $this->assertEquals(0, self::$repository->delete(10)); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws InvalidArgumentException - */ - public function testGetById() - { - $result = self::$repository->getById(1); - /** @var TrackData $data */ - $data = $result->getData(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertInstanceOf(TrackData::class, $data); - $this->assertEquals(1, $data->getId()); - $this->assertEquals(0, $data->getUserId()); - $this->assertEquals('1529145183', $data->getTime()); - $this->assertEquals('login', $data->getSource()); - $this->assertEquals('172.22.0.1', $data->getIpv4()); - - $this->assertEquals(0, self::$repository->getById(10)->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws InvalidArgumentException - */ - public function testAdd() - { - $data = new TrackRequest(time(), __METHOD__, 1); - $data->setTrackIp('192.168.0.1'); - - $this->assertEquals(7, self::$repository->add($data)); - - /** @var TrackData $resultData */ - $resultData = self::$repository->getById(7)->getData(); - - $this->assertEquals(7, $resultData->getId()); - $this->assertEquals($data->userId, $resultData->getUserId()); - $this->assertEquals($data->time, $resultData->getTime()); - $this->assertEquals($data->source, $resultData->getSource()); - $this->assertEquals('192.168.0.1', $resultData->getIpv4()); - } - - - /** - * @throws ConstraintException - * @throws QueryException - * @throws InvalidArgumentException - */ - public function testGetAll() - { - $result = self::$repository->getAll(); - /** @var TrackData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(6, $result->getNumRows()); - $this->assertCount(6, $data); - $this->assertInstanceOf(TrackData::class, $data[0]); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals(0, $data[0]->getUserId()); - $this->assertEquals('1529145183', $data[0]->getTime()); - $this->assertEquals('login', $data[0]->getSource()); - $this->assertEquals('172.22.0.1', $data[0]->getIpv4()); - $this->assertEquals('', $data[0]->getIpv6()); - } - - /** - * @throws ConstraintException - * @throws InvalidArgumentException - * @throws QueryException - */ - public function testGetTracksForClientFromTime() - { - $data = new TrackRequest(1529272367, 'login'); - $data->setTrackIp('172.22.0.1'); - - $result = self::$repository->getTracksForClientFromTime($data); - /** @var TrackData[] $resultData */ - $resultData = $result->getDataAsArray(); - - $this->assertEquals(3, $result->getNumRows()); - $this->assertCount(3, $resultData); - $this->assertInstanceOf(TrackData::class, $resultData[0]); - $this->assertEquals(4, $resultData[0]->getId()); - $this->assertInstanceOf(TrackData::class, $resultData[1]); - $this->assertEquals(5, $resultData[1]->getId()); - $this->assertInstanceOf(TrackData::class, $resultData[2]); - $this->assertEquals(6, $resultData[2]->getId()); - - $data->time = time(); - - $result = self::$repository->getTracksForClientFromTime($data); - - $this->assertEquals(0, $result->getNumRows()); - } - - public function testClear() - { - $this->markTestIncomplete(); - } - - public function testUnlock() - { - $this->markTestIncomplete(); - } - - public function testSearch() - { - $this->markTestIncomplete(); - } -} diff --git a/tests/SPT/Repositories/UserGroupRepositoryTest.php b/tests/SPT/Repositories/UserGroupRepositoryTest.php deleted file mode 100644 index 9403fd7b..00000000 --- a/tests/SPT/Repositories/UserGroupRepositoryTest.php +++ /dev/null @@ -1,356 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemSearchData; -use SP\DataModel\UserGroupData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\User\Ports\UserGroupRepositoryInterface; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\User\Repositories\UserGroupRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class UserGroupRepositoryTest - * - * Tests de integración para comprobar las consultas a la BBDD relativas a los grupos de usuarios - * - * @package SPT - */ -class UserGroupRepositoryTest extends DatabaseTestCase -{ - /** - * @var UserGroupRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(UserGroupRepository::class); - } - - /** - * Comprobar la obtención de uso del grupo por usuarios - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUsageByUsers() - { - $this->assertEquals(2, self::$repository->getUsageByUsers(1)->getNumRows()); - - $this->assertEquals(5, self::$repository->getUsageByUsers(2)->getNumRows()); - - $this->assertEquals(0, self::$repository->getUsageByUsers(10)->getNumRows()); - } - - /** - * Comprobar si el grupo está en uso - * - * @throws ConstraintException - * @throws QueryException - */ - public function testCheckInUse() - { - $this->assertTrue(self::$repository->checkInUse(1)); - - $this->assertTrue(self::$repository->checkInUse(2)); - - $this->assertFalse(self::$repository->checkInUse(5)); - } - - /** - * Comprobar la obtención de grupos por nombre - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByName() - { - $result = self::$repository->getByName('Demo'); - - $this->assertEquals(1, $result->getNumRows()); - - /** @var UserGroupData $data */ - $data = $result->getData(); - - $this->assertInstanceOf(UserGroupData::class, $data); - $this->assertEquals('Demo', $data->getName()); - $this->assertEmpty($data->getDescription()); - - $this->assertEquals(0, self::$repository->getByName('Prueba')->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(2, self::$repository->deleteByIdBatch([5, 6])); - - $this->assertEquals(4, self::getRowCount('UserGroup')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatchUsed() - { - // Se lanza excepción en caso de restricción relacional - $this->expectException(ConstraintException::class); - - self::$repository->deleteByIdBatch([1, 2]); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatchUnknown() - { - $this->assertEquals(2, self::$repository->deleteByIdBatch([5, 6, 10])); - - $this->assertEquals(4, self::getRowCount('UserGroup')); - } - - /** - * Comprobar la actualización de grupos - * - * @throws ConstraintException - * @throws DuplicatedItemException - * @throws QueryException - */ - public function testUpdate() - { - $data = new UserGroupData(); - $data->setId(2); - $data->setName('Grupo demo'); - $data->setDescription('Grupo para usuarios demo'); - - $this->assertEquals(1, self::$repository->update($data)); - - $this->expectException(DuplicatedItemException::class); - - $data->setName('Admins'); - - self::$repository->update($data); - - } - - /** - * Comprobar la obtención de grupos por Id - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $result = self::$repository->getById(2); - - $this->assertEquals(1, $result->getNumRows()); - - /** @var UserGroupData $data */ - $data = $result->getData(); - - $this->assertInstanceOf(UserGroupData::class, $data); - $this->assertEquals('Demo', $data->getName()); - $this->assertEmpty($data->getDescription()); - - $this->assertEquals(0, self::$repository->getById(10)->getNumRows()); - } - - /** - * Comprobar la creación de grupos - * - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testCreate() - { - $data = new UserGroupData(); - $data->setId(7); - $data->setName('Grupo Prueba'); - $data->setDescription('Grupo de prueba para usuarios'); - - $this->assertEquals($data->getId(), self::$repository->create($data)); - - $this->assertEquals($data, self::$repository->getById($data->getId())->getData()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testCreateDuplicated() - { - $data = new UserGroupData(); - $data->setName('Admins'); - $data->setDescription('Group for demo users'); - - $this->expectException(DuplicatedItemException::class); - - self::$repository->create($data); - } - - /** - * Comprobar la obtención de grupos - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $result = self::$repository->getAll(); - - $this->assertEquals(6, $result->getNumRows()); - - /** @var UserGroupData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertCount(6, $data); - - $this->assertInstanceOf(UserGroupData::class, $data[0]); - $this->assertEquals('Admins', $data[0]->getName()); - $this->assertEquals('sysPass Admins', $data[0]->getDescription()); - $this->assertInstanceOf(UserGroupData::class, $data[1]); - - $this->assertEquals('Demo', $data[1]->getName()); - $this->assertEmpty($data[1]->getDescription()); - } - - /** - * Comprobar la eliminación de grupos - * - * @throws SPException - */ - public function testDelete() - { - $this->assertEquals(1, self::$repository->delete(5)); - - $this->assertEquals(5, self::getRowCount('UserGroup')); - - $this->assertEquals(0, self::$repository->delete(10)); - } - - /** - * Comprobar la eliminación de grupos - * - * @throws SPException - */ - public function testDeleteUsed() - { - $this->expectException(ConstraintException::class); - - self::$repository->delete(1); - } - - /** - * Comprobar la obtención de uso de grupos - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUsage() - { - $this->assertEquals(7, self::$repository->getUsage(2)->getNumRows()); - - $this->assertEquals(3, self::$repository->getUsage(3)->getNumRows()); - - $this->assertEquals(0, self::$repository->getUsage(10)->getNumRows()); - } - - /** - * Comprobar la obtención de grupos en lote - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch(): void - { - $data = self::$repository->getByIdBatch([1, 2, 10])->getDataAsArray(); - - $this->assertCount(2, $data); - $this->assertInstanceOf(UserGroupData::class, $data[0]); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals('Admins', $data[0]->getName()); - $this->assertEquals('sysPass Admins', $data[0]->getDescription()); - - $this->assertInstanceOf(UserGroupData::class, $data[1]); - $this->assertEquals('Demo', $data[1]->getName()); - $this->assertEmpty($data[1]->getDescription()); - } - - /** - * Comprobar la búsqueda de grupos - * - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Demo'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(UserGroupData::class, $data[0]); - $this->assertEquals(2, $data[0]->id); - $this->assertEquals('Demo', $data[0]->name); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('prueba'); - - $result = self::$repository->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $result->getDataAsArray()); - } -} diff --git a/tests/SPT/Repositories/UserPassRecoverRepositoryTest.php b/tests/SPT/Repositories/UserPassRecoverRepositoryTest.php deleted file mode 100644 index a8724562..00000000 --- a/tests/SPT/Repositories/UserPassRecoverRepositoryTest.php +++ /dev/null @@ -1,129 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use Defuse\Crypto\Exception\EnvironmentIsBrokenException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\User\Ports\UserPassRecoverRepositoryInterface; -use SP\Infrastructure\User\Repositories\UserPassRecoverRepository; -use SP\Util\PasswordUtil; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class UserPassRecoverRepositoryTest - * - * @package SPT\Repositories - */ -class UserPassRecoverRepositoryTest extends DatabaseTestCase -{ - /** - * @var UserPassRecoverRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(UserPassRecoverRepository::class); - } - - /** - * @throws EnvironmentIsBrokenException - * @throws ConstraintException - * @throws QueryException - */ - public function testAdd() - { - $this->assertEquals(3, self::$repository->add(2, PasswordUtil::generateRandomBytes())); - - $this->expectException(ConstraintException::class); - - self::$repository->add(10, PasswordUtil::generateRandomBytes()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAttemptsByUserId() - { - $this->assertEquals(2, self::$repository->getAttemptsByUserId(2, 1529275206)); - - $this->assertEquals(0, self::$repository->getAttemptsByUserId(3, 1529275206)); - - $this->assertEquals(0, self::$repository->getAttemptsByUserId(10, 1529275206)); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws EnvironmentIsBrokenException - */ - public function testGetUserIdForHash() - { - $result = self::$repository->getUserIdForHash(pack('H*', '3038366162313036303866363838346566383031396134353237333561633066'), 1529275200); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertEquals(2, $result->getData()->userId); - - $result = self::$repository->getUserIdForHash(PasswordUtil::generateRandomBytes(), 1529275206); - - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws SPException - */ - public function testToggleUsedByHash() - { - $result = self::$repository->toggleUsedByHash(pack('H*', '3038366162313036303866363838346566383031396134353237333561633066'), 1529275200); - - $this->assertEquals(1, $result); - - $result = self::$repository->toggleUsedByHash(pack('H*', '3038366162313036303866363838346566383031396134353237333561633066'), 1529275200); - - $this->assertEquals(0, $result); - - $result = self::$repository->toggleUsedByHash(pack('H*', '3532383335346130663366626661376161626538303831373231653065633631'), 1529275331); - - $this->assertEquals(0, $result); - } -} diff --git a/tests/SPT/Repositories/UserProfileRepositoryTest.php b/tests/SPT/Repositories/UserProfileRepositoryTest.php deleted file mode 100644 index e627c070..00000000 --- a/tests/SPT/Repositories/UserProfileRepositoryTest.php +++ /dev/null @@ -1,293 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemSearchData; -use SP\DataModel\ProfileData; -use SP\DataModel\UserProfileData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\User\Ports\UserProfileRepositoryInterface; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\User\Repositories\UserProfileRepository; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class UserProfileRepositoryTest - * - * Tests de integración para comprobar las consultas a la BBDD relativas a los perfiles de usuarios - * - * @package SPT - */ -class UserProfileRepositoryTest extends DatabaseTestCase -{ - /** - * @var UserProfileRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(UserProfileRepository::class); - } - - /** - * Comprobar la obtención de perfiles - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $result = self::$repository->getAll(); - - $this->assertEquals(3, $result->getNumRows()); - - /** @var UserProfileData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertCount(3, $data); - - $this->assertInstanceOf(UserProfileData::class, $data[0]); - $this->assertEquals('Admin', $data[0]->getName()); - - $this->assertInstanceOf(UserProfileData::class, $data[1]); - $this->assertEquals('Demo', $data[1]->getName()); - } - - /** - * Comprobar la búsqueda de perfiles - * - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Demo'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(2, $data[0]->id); - $this->assertEquals('Demo', $data[0]->name); - - // Nueva búsqueda de perfil no existente - $itemSearchData->setSeachString('prueba'); - - $result = self::$repository->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $result->getDataAsArray()); - } - - /** - * Comprobar la actualización de perfiles - * - * @throws ConstraintException - * @throws DuplicatedItemException - * @throws QueryException - */ - public function testUpdate() - { - $data = new UserProfileData(); - $data->setId(2); - $data->setName('Test Profile Demo'); - - $this->assertEquals(1, self::$repository->update($data)); - - $this->expectException(DuplicatedItemException::class); - - $data->setName('Admin'); - - self::$repository->update($data); - } - - /** - * Comprobar la eliminación de perfiles - * - * @throws ConstraintException - * @throws QueryException - */ - public function testDelete() - { - $result = self::$repository->delete(3); - - $this->assertEquals(1, $result); - $this->assertEquals(2, self::getRowCount('UserProfile')); - - $this->expectException(ConstraintException::class); - - self::$repository->delete(1); - } - - /** - * Comprobar si el perfil está en uso - * - * @throws ConstraintException - * @throws QueryException - */ - public function testCheckInUse() - { - $this->assertTrue(self::$repository->checkInUse(1)); - $this->assertTrue(self::$repository->checkInUse(2)); - $this->assertFalse(self::$repository->checkInUse(3)); - } - - /** - * Comprobar la creación de perfiles - * - * @throws ConstraintException - * @throws DuplicatedItemException - * @throws QueryException - */ - public function testCreate() - { - $profileData = new ProfileData(); - $profileData->setAccAdd(true); - $profileData->setAccDelete(true); - $profileData->setConfigBackup(true); - - $data = new UserProfileData(); - $data->setId(4); - $data->setName('Prueba'); - $data->setProfile($profileData); - - $result = self::$repository->create($data); - - $this->assertEquals($data->getId(), $result); - $this->assertEquals(4, self::getRowCount('UserProfile')); - - /** @var UserProfileData $resultData */ - $resultData = self::$repository->getById($result)->getData(); - - $this->assertEquals($data->getId(), $resultData->getId()); - $this->assertEquals($data->getName(), $resultData->getName()); - $this->assertEquals(serialize($data->getProfile()), $resultData->getProfile()); - } - - /** - * @throws SPException - */ - public function testCreateDuplicated() - { - $data = new UserProfileData(); - $data->setName('Admin'); - $data->setProfile(new ProfileData()); - - $this->expectException(DuplicatedItemException::class); - - self::$repository->create($data); - } - - /** - * Comprobar la obtención de perfiles por Id - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $result = self::$repository->getById(2); - - $this->assertEquals(1, $result->getNumRows()); - - /** @var UserProfileData $data */ - $data = $result->getData(); - - $this->assertInstanceOf(UserProfileData::class, $data); - $this->assertEquals('Demo', $data->getName()); - $this->assertNotEmpty($data->getProfile()); - - $this->assertEquals(0, self::$repository->getById(4)->getNumRows()); - } - - /** - * Comprobar la obtención de los usuarios asociados a un perfil - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUsersForProfile() - { - $this->assertEquals(1, self::$repository->getUsersForProfile(2)->getNumRows()); - - $this->assertEquals(0, self::$repository->getUsersForProfile(3)->getNumRows()); - } - - /** - * Comprobar la obtención de perfiles en lote - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch() - { - $profiles = self::$repository->getByIdBatch([1, 2, 5])->getDataAsArray(); - - $this->assertCount(2, $profiles); - $this->assertInstanceOf(UserProfileData::class, $profiles[0]); - $this->assertEquals(1, $profiles[0]->getId()); - $this->assertEquals('Admin', $profiles[0]->getName()); - $this->assertInstanceOf(UserProfileData::class, $profiles[1]); - } - - /** - * Comprobar la eliminación de perfiles en lote - * - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - // Se lanza excepción en caso de restricción relacional - $this->expectException(ConstraintException::class); - - $result = self::$repository->deleteByIdBatch([1, 2, 3, 4]); - - $this->assertEquals(1, $result); - } -} diff --git a/tests/SPT/Repositories/UserRepositoryTest.php b/tests/SPT/Repositories/UserRepositoryTest.php deleted file mode 100644 index 4ca58c3f..00000000 --- a/tests/SPT/Repositories/UserRepositoryTest.php +++ /dev/null @@ -1,446 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Core\Crypt\Crypt; -use SP\Core\Crypt\Hash; -use SP\DataModel\ItemSearchData; -use SP\DataModel\UserData; -use SP\DataModel\UserPreferencesData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\User\Ports\UserRepositoryInterface; -use SP\Domain\User\Services\UpdatePassRequest; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\User\Repositories\UserRepository; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class UserRepositoryTest - * - * Tests de integración para comprobar las consultas a la BBDD relativas a los usuarios - * - * @package SPT - */ -class UserRepositoryTest extends DatabaseTestCase -{ - - /** - * @var UserRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(UserRepository::class); - } - - /** - * Comprobar la actualización de usuarios - * - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdate() - { - $userData = new UserData(); - $userData->setId(2); - $userData->setName('Usuario Demo'); - $userData->setLogin('demo'); - $userData->setEmail('demo@syspass.org'); - $userData->setNotes('Usuario Demo'); - $userData->setUserGroupId(1); - $userData->setUserProfileId(1); - $userData->setIsAdminApp(1); - $userData->setIsAdminAcc(1); - $userData->setIsDisabled(1); - $userData->setIsChangePass(1); - $userData->setIsLdap(0); - - $this->assertEquals(1, self::$repository->update($userData)); - - $userData->setId(3); - - $this->expectException(DuplicatedItemException::class); - - self::$repository->update($userData); - - $userData->setId(10); - - $this->assertEquals(0, self::$repository->update($userData)); - } - - /** - * Comprobar la modificación de las preferencias de usuario - * - * @throws QueryException - * @throws ConstraintException - */ - public function testUpdatePreferencesById() - { - $preferences = new UserPreferencesData(); - $preferences->setLang('es_ES'); - $preferences->setAccountLink(true); - $preferences->setOptionalActions(true); - $preferences->setResultsAsCards(true); - $preferences->setResultsPerPage(10); - - $this->assertEquals(1, self::$repository->updatePreferencesById(2, $preferences)); - } - - /** - * Comprobar la obtención de los datos de un usuario - * - * @throws SPException - */ - public function testGetById() - { - $result = self::$repository->getById(2); - - $this->assertEquals(1, $result->getNumRows()); - - /** @var UserData $data */ - $data = $result->getData(); - - $this->assertInstanceOf(UserData::class, $data); - $this->assertEquals('sysPass demo', $data->getName()); - $this->assertEquals('demo', $data->getLogin()); - - $result = self::$repository->getById(10); - - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * Comprobar si existe un usuario - * - * @throws QueryException - * @throws ConstraintException - */ - public function testCheckExistsByLogin() - { - $this->assertTrue(self::$repository->checkExistsByLogin('demo')); - $this->assertFalse(self::$repository->checkExistsByLogin('usuario')); - } - - /** - * Comprobar los datos de uso de un usuario - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUsageForUser() - { - $result = self::$repository->getUsageForUser(2); - - $this->assertEquals(2, $result->getNumRows()); - - $this->assertCount(2, $result->getDataAsArray()); - } - - /** - * Comprobar la actualización de la clave de un usuario por Id - * - * @throws QueryException - * @throws ConstraintException - * @throws SPException - */ - public function testUpdatePassById() - { - $result = self::$repository->updatePassById(2, new UpdatePassRequest(Hash::hashKey('test123'))); - - $this->assertEquals(1, $result); - - /** @var UserData $data */ - $data = self::$repository->getById(2)->getData(); - - $this->assertTrue(Hash::checkHashKey('test123', $data->getPass())); - - $result = self::$repository->updatePassById(10, new UpdatePassRequest(Hash::hashKey('test123'))); - - $this->assertEquals(0, $result); - } - - /** - * Obtener los datos de los usuarios por Id en lote - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch() - { - $users = self::$repository->getByIdBatch([1, 2, 10])->getDataAsArray(); - - $this->assertCount(2, $users); - $this->assertInstanceOf(UserData::class, $users[0]); - $this->assertEquals('admin', $users[0]->getLogin()); - $this->assertInstanceOf(UserData::class, $users[1]); - } - - /** - * Obtener los datos de todos los usuarios - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $users = self::$repository->getAll(); - - $this->assertCount(5, $users); - $this->assertInstanceOf(UserData::class, $users[0]); - $this->assertEquals('admin', $users[0]->getLogin()); - } - - /** - * Actualizar un usuario desde el proceso de login - * - * @throws QueryException - * @throws ConstraintException - */ - public function testUpdateOnLogin() - { - $userData = new UserData(); - $userData->setPass(Hash::hashKey('prueba123')); - $userData->setName('prueba'); - $userData->setEmail('prueba@syspass.org'); - $userData->setIsLdap(1); - $userData->setLogin('demo'); - - $this->assertEquals(1, self::$repository->updateOnLogin($userData)); - - $userData->setLogin('demodedadae'); - - $this->assertEquals(0, self::$repository->updateOnLogin($userData)); - } - - /** - * Eliminar usuarios en lote - * - * @throws QueryException - * @throws ConstraintException - */ - public function testDeleteByIdBatch() - { - $this->expectException(ConstraintException::class); - - $result = self::$repository->deleteByIdBatch([1, 2, 5]); - - $this->assertCount(2, $result); - } - - /** - * Comprobar la obtención de los datos de un usuario - * - * @throws SPException - */ - public function testGetByLogin() - { - $result = self::$repository->getByLogin('demo'); - - $this->assertEquals(1, $result->getNumRows()); - - /** @var UserData $data */ - $data = $result->getData(); - - $this->assertInstanceOf(UserData::class, $data); - $this->assertEquals('sysPass demo', $data->getName()); - $this->assertEquals('demo', $data->getLogin()); - - $this->assertEquals(0, self::$repository->getByLogin('prueba')->getNumRows()); - } - - /** - * Comprobar la eliminación de usuarios - * - * @throws QueryException - * @throws ConstraintException - */ - public function testDelete() - { - $result = self::$repository->delete(4); - - $this->assertEquals(1, $result); - $this->assertEquals(4, self::getRowCount('User')); - - $this->expectException(ConstraintException::class); - - self::$repository->delete(1); - } - - /** - * Comprobar la obtención de los datos de usuarios - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetBasicInfo() - { - $result = self::$repository->getBasicInfo(); - - $this->assertEquals(5, $result->getNumRows()); - - $data = $result->getDataAsArray(); - - $this->assertCount(5, $data); - $this->assertInstanceOf(UserData::class, $data[0]); - } - - /** - * Comprobar la modificación de los datos del último login - * - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdateLastLoginById() - { - $this->assertEquals(1, self::$repository->updateLastLoginById(2)); - - $this->assertEquals(0, self::$repository->updateLastLoginById(10)); - } - - /** - * Comprobar la búsqueda de usuarios mediante texto - * - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('User A'); - - $result = self::$repository->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(3, $data[0]->id); - $this->assertEquals('User A', $data[0]->name); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('prueba'); - - $result = self::$repository->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $result->getDataAsArray()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws CryptoException - * @throws SPException - */ - public function testUpdateMasterPassById() - { - $key = Crypt::makeSecuredKey('prueba123'); - $pass = Crypt::encrypt('prueba_key', $key, 'prueba123'); - - $this->assertEquals(1, self::$repository->updateMasterPassById(3, $pass, $key)); - - $result = self::$repository->getById(3); - - $this->assertEquals(1, $result->getNumRows()); - - /** @var UserData $data */ - $data = $result->getData(); - - $this->assertEquals($pass, $data->getMPass()); - $this->assertEquals($key, $data->getMKey()); - } - - /** - * Comprobar la creación de usuarios - * - * @throws SPException - */ - public function testCreate() - { - $userData = new UserData(); - $userData->setName('Usuario Prueba'); - $userData->setLogin('prueba'); - $userData->setEmail('prueba@syspass.org'); - $userData->setNotes('Usuario Prueba'); - $userData->setUserGroupId(1); - $userData->setUserProfileId(1); - $userData->setIsAdminApp(1); - $userData->setIsAdminAcc(1); - $userData->setIsDisabled(1); - $userData->setIsChangePass(1); - $userData->setIsLdap(0); - $userData->setPass(Hash::hashKey('prueba123')); - - $this->assertEquals(6, self::$repository->create($userData)); - - $userData->setLogin('demo'); - $userData->setEmail('prueba@syspass.org'); - - $this->expectException(DuplicatedItemException::class); - - self::$repository->create($userData); - - $userData->setLogin('prueba'); - $userData->setEmail('demo@syspass.org'); - - self::$repository->create($userData); - } - - /** - * Comprobar la obtención de email de usuario por Id de grupo - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUserEmailForGroup() - { - $this->assertEquals(4, self::$repository->getUserEmailForGroup(2)->getNumRows()); - - $this->assertEquals(0, self::$repository->getUserEmailForGroup(10)->getNumRows()); - } -} diff --git a/tests/SPT/Repositories/UserToUserGroupRepositoryTest.php b/tests/SPT/Repositories/UserToUserGroupRepositoryTest.php deleted file mode 100644 index 1a877b67..00000000 --- a/tests/SPT/Repositories/UserToUserGroupRepositoryTest.php +++ /dev/null @@ -1,232 +0,0 @@ -. - */ - -namespace SPT\Repositories; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\UserToUserGroupData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\User\Ports\UserToUserGroupRepositoryInterface; -use SP\Infrastructure\User\Repositories\UserToUserGroupRepository; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class UserToUserGroupRepositoryTest - * - * @package SPT\SP\Infrastructure\Common\Repositories - */ -class UserToUserGroupRepositoryTest extends DatabaseTestCase -{ - /** - * @var UserToUserGroupRepositoryInterface - */ - private static $repository; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$repository = $dic->get(UserToUserGroupRepository::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetGroupsForUser() - { - $result = self::$repository->getGroupsForUser(3); - - $this->assertEquals(1, $result->getNumRows()); - - $data = $result->getDataAsArray(); - - $this->assertCount(1, $data); - $this->assertEquals(2, $data[0]->userGroupId); - - $result = self::$repository->getGroupsForUser(2); - - $this->assertEquals(1, $result->getNumRows()); - - $data = $result->getDataAsArray(); - - $this->assertCount(1, $data); - $this->assertEquals(1, $data[0]->userGroupId); - - $this->assertEquals(0, self::$repository->getGroupsForUser(10)->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdate() - { - $data = [3, 4]; - - self::$repository->update(1, $data); - - $result = self::$repository->getById(1); - - $this->assertEquals(2, $result->getNumRows()); - - /** @var UserToUserGroupData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertInstanceOf(UserToUserGroupData::class, $data[0]); - $this->assertEquals(1, $data[0]->getUserGroupId()); - $this->assertEquals(3, $data[0]->getUserId()); - - $this->assertInstanceOf(UserToUserGroupData::class, $data[1]); - $this->assertEquals(1, $data[1]->getUserGroupId()); - $this->assertEquals(4, $data[1]->getUserId()); - - $this->expectException(ConstraintException::class); - - self::$repository->update(10, [3, 4]); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $result = self::$repository->getById(2); - - $this->assertEquals(2, $result->getNumRows()); - - /** @var UserToUserGroupData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertCount(2, $data); - - $this->assertInstanceOf(UserToUserGroupData::class, $data[0]); - $this->assertEquals(2, $data[0]->getUserGroupId()); - $this->assertEquals(1, $data[0]->getUserId()); - - $this->assertInstanceOf(UserToUserGroupData::class, $data[1]); - $this->assertEquals(2, $data[1]->getUserGroupId()); - $this->assertEquals(3, $data[1]->getUserId()); - - $data = self::$repository->getById(1)->getDataAsArray(); - - $this->assertCount(1, $data); - - $this->assertInstanceOf(UserToUserGroupData::class, $data[0]); - $this->assertEquals(1, $data[0]->getUserGroupId()); - $this->assertEquals(2, $data[0]->getUserId()); - - $this->assertEquals(0, self::$repository->getById(10)->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDelete() - { - $this->assertEquals(1, self::$repository->delete(1)); - - $this->assertEquals(2, self::$repository->delete(2)); - - $this->assertEquals(0, self::$repository->delete(10)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testAdd() - { - $data = [3, 4]; - - self::$repository->add(1, $data); - - $result = self::$repository->getById(1); - - $this->assertEquals(3, $result->getNumRows()); - - /** @var UserToUserGroupData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertCount(3, $data); - - $this->assertInstanceOf(UserToUserGroupData::class, $data[0]); - - $this->assertEquals(1, $data[0]->getUserGroupId()); - $this->assertEquals(2, $data[0]->getUserId()); - - $this->assertInstanceOf(UserToUserGroupData::class, $data[1]); - $this->assertEquals(1, $data[1]->getUserGroupId()); - $this->assertEquals(3, $data[1]->getUserId()); - - $this->assertInstanceOf(UserToUserGroupData::class, $data[1]); - $this->assertEquals(1, $data[2]->getUserGroupId()); - $this->assertEquals(4, $data[2]->getUserId()); - - $this->expectException(ConstraintException::class); - - self::$repository->add(10, [3, 4]); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testAddDuplicated() - { - $data = [2, 3, 4]; - - $this->expectException(ConstraintException::class); - - self::$repository->add(1, $data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCheckUserInGroup() - { - $this->assertTrue(self::$repository->checkUserInGroup(1, 2)); - - $this->assertTrue(self::$repository->checkUserInGroup(2, 3)); - - $this->assertFalse(self::$repository->checkUserInGroup(3, 3)); - } -} diff --git a/tests/SPT/Services/Api/ApiRequestTest.php b/tests/SPT/Services/Api/ApiRequestTest.php deleted file mode 100644 index 6f1bb724..00000000 --- a/tests/SPT/Services/Api/ApiRequestTest.php +++ /dev/null @@ -1,105 +0,0 @@ -. - */ - -namespace SPT\Services\Api; - -use PHPUnit\Framework\TestCase; -use SP\Domain\Api\Services\ApiRequest; -use SP\Domain\Api\Services\ApiRequestException; - -use function SPT\getResource; - -/** - * Class ApiRequestTest - * - * @package SPT\Services\Api - */ -class ApiRequestTest extends TestCase -{ - /** - * @throws ApiRequestException - */ - public function testGetRequestJsonData() - { - $apiRequest = new ApiRequest(getResource('json', 'account_search.json')); - $this->assertEquals(10, $apiRequest->getId()); - $this->assertEquals('account/search', $apiRequest->getMethod()); - $this->assertEquals('2cee8b224f48e01ef48ac172e879cc7825800a9d7ce3b23783212f4758f1c146', $apiRequest->get('authToken')); - $this->assertEquals('API', $apiRequest->get('text')); - $this->assertEquals(5, $apiRequest->get('count')); - $this->assertEquals(1, $apiRequest->get('clientId')); - $this->assertEquals(1, $apiRequest->get('categoryId')); - - } - - /** - * @throws ApiRequestException - */ - public function testWrongJson() - { - $this->expectException(ApiRequestException::class); - $this->expectExceptionCode(-32700); - - $wrongJson = '{abc}'; - new ApiRequest($wrongJson); - } - - /** - * testWrongJsonParams - */ - public function testWrongJsonParams() - { - $this->checkJsonException('{"a": 1}'); - $this->checkJsonException('{"jsonrpc": 2.0}'); - $this->checkJsonException('{"jsonrpc": 2.0, "method": "account/search"}'); - $this->checkJsonException('{"jsonrpc": 2.0, "method": "account/search", "params": {}}'); - $this->checkJsonException('{"jsonrpc": 2.0, "method": "account/search", "params": {"authToken": "1"}}'); - } - - /** - * @throws ApiRequestException - */ - public function testFilterData() - { - $json = '{"jsonrpc": 2.0, "method": "&account/$(search)?!%()=?¿", "params": {"authToken": "1"}, "id": "10"}'; - - $apiRequest = new ApiRequest($json); - $this->assertEquals(10, $apiRequest->getId()); - $this->assertEquals('account/search', $apiRequest->getMethod()); - } - - /** - * @param $json - */ - private function checkJsonException($json) - { - try { - new ApiRequest($json); - - $this->fail('No exception thrown'); - } catch (ApiRequestException $e) { - $this->assertEquals(-32600, $e->getCode()); - } - } -} diff --git a/tests/SPT/Services/Api/ApiServiceTest.php b/tests/SPT/Services/Api/ApiServiceTest.php deleted file mode 100644 index 9ca904d1..00000000 --- a/tests/SPT/Services/Api/ApiServiceTest.php +++ /dev/null @@ -1,205 +0,0 @@ -. - */ - -namespace SPT\Services\Api; - -use Closure; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Domain\Api\Ports\ApiServiceInterface; -use SP\Domain\Api\Services\ApiRequest; -use SP\Domain\Api\Services\ApiService; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Acl\AclActionsInterface; -use SP\Domain\Core\Exceptions\SPException; -use SPT\DatabaseTestCase; - -use function SPT\getResource; -use function SPT\setupContext; - -/** - * Class ApiServiceTest - * - * @package SPT\Services - */ -class ApiServiceTest extends DatabaseTestCase -{ - public const ADMIN_TOKEN = '2cee8b224f48e01ef48ac172e879cc7825800a9d7ce3b23783212f4758f1c146'; - public const ADMIN_PASS = '123456'; - public const DEMO_TOKEN = '12b9027d24efff7bfbaca8bd774a4c34b45de35e033d2b192a88f4dfaee5c233'; - - /** - * @var ApiServiceInterface - */ - private static $service; - /** - * @var Closure - */ - private static $changeRequest; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(ApiService::class); - - self::$changeRequest = function (string $request) use ($dic) { - $dic->set(ApiRequest::class, new ApiRequest($request)); - }; - } - - /** - * @throws ServiceException - * @throws SPException - */ - public function testSetup() - { - self::$changeRequest->call($this, getResource('json', 'account_search.json')); - - self::$service->setup(AclActionsInterface::ACCOUNT_SEARCH); - - $this->assertTrue(self::$service->isInitialized()); - - self::$service->setup(AclActionsInterface::ACCOUNT_VIEW); - - $this->assertTrue(self::$service->isInitialized()); - - self::$service->setup(AclActionsInterface::ACCOUNT_DELETE); - - $this->assertTrue(self::$service->isInitialized()); - - self::$changeRequest->call($this, getResource('json', 'account_viewPass.json')); - - self::$service->setup(AclActionsInterface::ACCOUNT_VIEW_PASS); - - $this->assertTrue(self::$service->isInitialized()); - - $this->expectException(ServiceException::class); - - self::$service->setup(AclActionsInterface::ACCOUNT_CREATE); - } - - /** - * @throws ServiceException - * @throws SPException - */ - public function testGetParam() - { - self::$changeRequest->call($this, getResource('json', 'account_search.json')); - - self::$service->setup(AclActionsInterface::ACCOUNT_SEARCH); - - $this->assertEquals('2cee8b224f48e01ef48ac172e879cc7825800a9d7ce3b23783212f4758f1c146', self::$service->getParam('authToken')); - $this->assertEquals('API', self::$service->getParam('text')); - $this->assertEquals('5', self::$service->getParam('count')); - $this->assertEquals('1', self::$service->getParam('categoryId')); - $this->assertEquals('1', self::$service->getParam('clientId')); - - $this->assertNull(self::$service->getParam('test')); - - $this->expectException(ServiceException::class); - $this->expectExceptionCode(-32602); - - self::$service->getParam('test', true); - } - - /** - * @throws ServiceException - * @throws SPException - */ - public function testGetParamInt() - { - self::$changeRequest->call($this, getResource('json', 'account_search.json')); - - self::$service->setup(AclActionsInterface::ACCOUNT_SEARCH); - - $this->assertEquals(1, self::$service->getParamInt('categoryId')); - $this->assertEquals(0, self::$service->getParamInt('text')); - } - - /** - */ - public function testGetParamEmail() - { - $this->markTestIncomplete(); - } - - /** - * @throws ServiceException - * @throws SPException - */ - public function testGetParamString() - { - self::$changeRequest->call($this, getResource('json', 'account_add.json')); - - self::$service->setup(AclActionsInterface::ACCOUNT_SEARCH); - - $this->assertEquals("bla bla bla\nbla bla~!?|.$%&/()=¿ªº€\"'", self::$service->getParamString('notes')); - - $this->assertEmpty(self::$service->getParamString('test')); - } - - /** - * @throws ServiceException - * @throws SPException - */ - public function testGetParamRaw() - { - self::$changeRequest->call($this, getResource('json', 'account_add.json')); - - self::$service->setup(AclActionsInterface::ACCOUNT_SEARCH); - - $this->assertEquals("bla bla bla\nbla bla~!?|.$%&/()=¿ªº€\"'", self::$service->getParamRaw('notes')); - } - - /** - * @throws ServiceException - * @throws SPException - */ - public function testGetRequestId() - { - self::$changeRequest->call($this, getResource('json', 'account_search.json')); - - self::$service->setup(AclActionsInterface::ACCOUNT_SEARCH); - - $this->assertEquals(10, self::$service->getRequestId()); - } - - /** - * @throws ServiceException - */ - public function testGetMasterPass() - { - $this->assertEquals('12345678900', self::$service->getMasterPass()); - } -} diff --git a/tests/SPT/Services/AuthToken/AuthTokenServiceTest.php b/tests/SPT/Services/AuthToken/AuthTokenServiceTest.php deleted file mode 100644 index 1554c944..00000000 --- a/tests/SPT/Services/AuthToken/AuthTokenServiceTest.php +++ /dev/null @@ -1,305 +0,0 @@ -. - */ - -namespace SPT\Services\AuthToken; - -use Defuse\Crypto\Exception\CryptoException; -use Defuse\Crypto\Exception\EnvironmentIsBrokenException; -use DI\DependencyException; -use DI\NotFoundException; -use Exception; -use SP\Core\Context\ContextException; -use SP\Core\Crypt\Hash; -use SP\Core\Crypt\Vault; -use SP\DataModel\AuthToken; -use SP\DataModel\ItemSearchData; -use SP\Domain\Auth\Services\AuthTokenService; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Acl\AclActionsInterface; -use SP\Domain\Core\Crypt\VaultInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SP\Util\Util; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class AuthTokenServiceTest - * - * @package SPT\Services\AuthToken - */ -class AuthTokenServiceTest extends DatabaseTestCase -{ - public const AUTH_TOKEN = '2cee8b224f48e01ef48ac172e879cc7825800a9d7ce3b23783212f4758f1c146'; - public const AUTH_TOKEN_PASS = 123456; - - /** - * @var AuthTokenService - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(AuthTokenService::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDelete() - { - self::$service->delete(1); - - $this->expectException(NoSuchItemException::class); - - self::$service->delete(10); - - $this->assertEquals(4, self::getRowCount('AuthToken')); - } - - /** - * @throws ServiceException - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(2, self::$service->deleteByIdBatch([1, 2])); - - $this->assertEquals(0, self::$service->deleteByIdBatch([])); - - $this->expectException(ServiceException::class); - - self::$service->deleteByIdBatch([3, 10]); - - $this->assertEquals(2, self::getRowCount('AuthToken')); - - } - - /** - * @throws Exception - */ - public function testRefreshAndUpdate() - { - $data = new AuthToken(); - $data->setId(1); - $data->setActionId(AclActionsInterface::ACCOUNT_CREATE); - $data->setCreatedBy(1); - $data->setHash(self::AUTH_TOKEN_PASS); - $data->setUserId(2); - - self::$service->refreshAndUpdate($data); - - $resultData = self::$service->getById(1); - - $vault = Util::unserialize(Vault::class, $resultData->getVault()); - - $this->assertEquals('12345678900', $vault->getData(self::AUTH_TOKEN_PASS . $resultData->getToken())); - - $this->expectException(NoSuchItemException::class); - - $data->setId(10); - $data->setActionId(AclActionsInterface::ACCOUNT_DELETE); - - $this->assertEquals(0, self::$service->refreshAndUpdate($data)); - } - - /** - * @throws ServiceException - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - */ - public function testGetTokenByToken() - { - $data = self::$service->getTokenByToken(AclActionsInterface::ACCOUNT_VIEW_PASS, self::AUTH_TOKEN); - - $this->assertInstanceOf(AuthToken::class, $data); - $this->assertEquals(2, $data->getId()); - $this->assertEquals(AclActionsInterface::ACCOUNT_VIEW_PASS, $data->getActionId()); - $this->assertTrue(Hash::checkHashKey(self::AUTH_TOKEN_PASS, $data->getHash())); - $this->assertNotEmpty($data->getVault()); - - /** @var VaultInterface $vault */ - $vault = Util::unserialize(Vault::class, $data->getVault()); - $this->assertEquals('12345678900', $vault->getData(self::AUTH_TOKEN_PASS . self::AUTH_TOKEN)); - - $this->expectException(CryptoException::class); - - $vault->getData(1234); - } - - /** - * @throws CryptoException - * @throws ServiceException - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdate() - { - $data = new AuthToken(); - $data->setId(1); - $data->setActionId(AclActionsInterface::ACCOUNT_CREATE); - $data->setCreatedBy(1); - $data->setHash(self::AUTH_TOKEN_PASS); - $data->setUserId(2); - - self::$service->update($data); - - $data = self::$service->getTokenByToken(AclActionsInterface::ACCOUNT_CREATE, $data->getToken()); - - $this->assertInstanceOf(AuthToken::class, $data); - $this->assertEquals(AclActionsInterface::ACCOUNT_CREATE, $data->getActionId()); - $this->assertTrue(Hash::checkHashKey(self::AUTH_TOKEN_PASS, $data->getHash())); - $this->assertEquals(2, $data->getUserId()); - - $vault = Util::unserialize(Vault::class, $data->getVault()); - - $this->assertEquals('12345678900', $vault->getData(self::AUTH_TOKEN_PASS . $data->getToken())); - - $this->expectException(NoSuchItemException::class); - - $data->setId(10); - $data->setUserId(1); - - self::$service->update($data); - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - */ - public function testGetById() - { - $data = self::$service->getById(1); - - $this->assertInstanceOf(AuthToken::class, $data); - $this->assertEquals(1, $data->getId()); - $this->assertEquals(AclActionsInterface::ACCOUNT_SEARCH, $data->getActionId()); - $this->assertEquals(pack('H*', '31326239303237643234656666663762666261636138626437373461346333346234356465333565303333643262313932613838663464666165653563323333'), $data->getToken()); - $this->assertNull($data->getHash()); - - $data = self::$service->getById(2); - - $this->assertInstanceOf(AuthToken::class, $data); - $this->assertEquals(2, $data->getId()); - $this->assertEquals(AclActionsInterface::ACCOUNT_VIEW_PASS, $data->getActionId()); - $this->assertEquals(self::AUTH_TOKEN, $data->getToken()); - $this->assertTrue(Hash::checkHashKey(self::AUTH_TOKEN_PASS, $data->getHash())); - - $vault = Util::unserialize(Vault::class, $data->getVault()); - - $this->assertEquals('12345678900', $vault->getData(self::AUTH_TOKEN_PASS . $data->getToken())); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('admin'); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(4, $result->getNumRows()); - $this->assertCount(4, $data); - - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(AclActionsInterface::ACCOUNT_SEARCH, $data[0]->actionId); - $this->assertEquals(self::AUTH_TOKEN, $data[0]->token); - - $this->assertInstanceOf(stdClass::class, $data[1]); - $this->assertEquals(AclActionsInterface::ACCOUNT_VIEW, $data[1]->actionId); - $this->assertEquals(self::AUTH_TOKEN, $data[1]->token); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setSeachString('test'); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $result->getDataAsArray()); - } - - /** - * @throws CryptoException - * @throws ServiceException - * @throws EnvironmentIsBrokenException - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testCreate() - { - $authTokenData = new AuthToken(); - $authTokenData->setActionId(AclActionsInterface::ACCOUNT_CREATE); - $authTokenData->setCreatedBy(1); - $authTokenData->setHash(self::AUTH_TOKEN_PASS); - $authTokenData->setUserId(2); - - $this->assertEquals(6, self::$service->create($authTokenData)); - $this->assertEquals(6, self::getRowCount('AuthToken')); - - $data = self::$service->getTokenByToken(AclActionsInterface::ACCOUNT_CREATE, $authTokenData->getToken()); - - $this->assertInstanceOf(AuthToken::class, $data); - $this->assertEquals(AclActionsInterface::ACCOUNT_CREATE, $data->getActionId()); - $this->assertTrue(Hash::checkHashKey(self::AUTH_TOKEN_PASS, $data->getHash())); - $this->assertEquals(6, $data->getId()); - $this->assertEquals(2, $data->getUserId()); - - $vault = Util::unserialize(Vault::class, $data->getVault()); - - $this->assertEquals('12345678900', $vault->getData(self::AUTH_TOKEN_PASS . $data->getToken())); - - $this->expectException(DuplicatedItemException::class); - - $authTokenData->setUserId(2); - - self::$service->create($authTokenData); - } -} diff --git a/tests/SPT/Services/Category/CategoryServiceTest.php b/tests/SPT/Services/Category/CategoryServiceTest.php deleted file mode 100644 index 32ac0e80..00000000 --- a/tests/SPT/Services/Category/CategoryServiceTest.php +++ /dev/null @@ -1,277 +0,0 @@ -. - */ - -namespace SPT\Services\Category; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\CategoryData; -use SP\DataModel\ItemSearchData; -use SP\Domain\Category\Ports\CategoryServiceInterface; -use SP\Domain\Category\Services\CategoryService; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class CategoryServiceTest - * - * @package SPT\Services\Category - */ -class CategoryServiceTest extends DatabaseTestCase -{ - /** - * @var CategoryServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$service = $dic->get(CategoryService::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('linux'); - - $result = self::$service->search($itemSearchData); - - $data = $result->getDataAsArray(); - - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(2, $data[0]->id); - $this->assertEquals('Linux server', $data[0]->description); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('prueba'); - - $this->assertEquals(0, self::$service->search($itemSearchData)->getNumRows()); - } - - /** - * @throws NoSuchItemException - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByName() - { - $data = self::$service->getByName('Web'); - - $this->assertEquals(1, $data->getId()); - $this->assertEquals('Web sites', $data->getDescription()); - - $data = self::$service->getByName('Linux'); - - $this->assertEquals(2, $data->getId()); - $this->assertEquals('Linux server', $data->getDescription()); - - // Se comprueba que el hash generado es el mismo en para el nombre 'Web' - $data = self::$service->getByName(' web. '); - - $this->assertEquals(1, $data->getId()); - $this->assertEquals('Web sites', $data->getDescription()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getByName('Prueba'); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllBasic() - { - $count = self::getRowCount('Category'); - - $data = self::$service->getAllBasic(); - - $this->assertCount($count, $data); - - $this->assertInstanceOf(CategoryData::class, $data[0]); - $this->assertEquals('Linux', $data[0]->getName()); - - $this->assertInstanceOf(CategoryData::class, $data[1]); - $this->assertEquals('SSH', $data[1]->getName()); - - $this->assertInstanceOf(CategoryData::class, $data[2]); - $this->assertEquals('Web', $data[2]->getName()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testDeleteByIdBatch() - { - $countBefore = self::getRowCount('Category'); - - $this->assertEquals(1, self::$service->deleteByIdBatch([3])); - - $countAfter = self::getRowCount('Category'); - - $this->assertEquals($countBefore - 1, $countAfter); - - // Comprobar que se produce una excepción al tratar de eliminar categorías usadas - $this->expectException(ConstraintException::class); - - $this->assertEquals(1, self::$service->deleteByIdBatch([1, 2, 3])); - } - - /** - * @throws ConstraintException - * @throws DuplicatedItemException - * @throws NoSuchItemException - * @throws QueryException - * @throws SPException - */ - public function testCreate() - { - $countBefore = self::getRowCount('Category'); - - $data = new CategoryData(); - $data->name = 'Categoría prueba'; - $data->description = 'Descripción prueba'; - - $id = self::$service->create($data); - - // Comprobar que el Id devuelto corresponde con la categoría creada - $result = self::$service->getById($id); - - $this->assertEquals($data->name, $result->getName()); - $this->assertEquals($data->description, $result->getDescription()); - - $countAfter = self::getRowCount('Category'); - - $this->assertEquals($countBefore + 1, $countAfter); - - $this->expectException(DuplicatedItemException::class); - - self::$service->create($data); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - * @throws SPException - */ - public function testUpdate() - { - $data = new CategoryData(); - $data->id = 1; - $data->name = 'Web prueba'; - $data->description = 'Descripción web prueba'; - - self::$service->update($data); - - $result = self::$service->getById(1); - - $this->assertEquals($data->name, $result->getName()); - $this->assertEquals($data->description, $result->getDescription()); - - // Comprobar la a actualización con un nombre duplicado comprobando su hash - $data = new CategoryData(); - $data->id = 1; - $data->name = ' linux.'; - - $this->expectException(DuplicatedItemException::class); - - self::$service->update($data); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetById() - { - $data = self::$service->getById(1); - - $this->assertEquals('Web', $data->getName()); - $this->assertEquals('Web sites', $data->getDescription()); - - $data = self::$service->getById(2); - - $this->assertEquals('Linux', $data->getName()); - $this->assertEquals('Linux server', $data->getDescription()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getById(10); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testDelete() - { - $countBefore = self::getRowCount('Category'); - - self::$service->delete(3); - - $countAfter = self::getRowCount('Category'); - - $this->assertEquals($countBefore - 1, $countAfter); - - // Comprobar que se produce una excepción al tratar de eliminar categorías usadas - $this->expectException(ConstraintException::class); - - self::$service->delete(2); - - $this->expectException(NoSuchItemException::class); - - self::$service->delete(10); - } -} diff --git a/tests/SPT/Services/Client/ClientServiceTest.php b/tests/SPT/Services/Client/ClientServiceTest.php deleted file mode 100644 index 169758c3..00000000 --- a/tests/SPT/Services/Client/ClientServiceTest.php +++ /dev/null @@ -1,317 +0,0 @@ -. - */ - -namespace SPT\Services\Client; - -use Closure; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ClientData; -use SP\DataModel\ItemSearchData; -use SP\Domain\Client\Ports\ClientServiceInterface; -use SP\Domain\Client\Services\ClientService; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Context\ContextInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\User\Services\UserLoginResponse; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class ClientServiceTest - * - * @package SPT\Services\Client - */ -class ClientServiceTest extends DatabaseTestCase -{ - /** - * @var Closure - */ - private static $setupUser; - /** - * @var ClientServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(ClientService::class); - - self::$setupUser = function (UserLoginResponse $response) use ($dic) { - $response->setLastUpdate(time()); - - $dic->get(ContextInterface::class)->setUserData($response); - }; - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('google'); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(ClientData::class, $data[0]); - $this->assertEquals(1, $data[0]->id); - $this->assertEquals('Google Inc.', $data[0]->description); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('prueba'); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $result->getDataAsArray()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllBasic() - { - $count = self::getRowCount('Client'); - - $results = self::$service->getAllBasic(); - - $this->assertCount($count, $results); - - $this->assertInstanceOf(ClientData::class, $results[0]); - $this->assertEquals('Amazon', $results[0]->getName()); - - $this->assertInstanceOf(ClientData::class, $results[1]); - $this->assertEquals('Apple', $results[1]->getName()); - - $this->assertInstanceOf(ClientData::class, $results[2]); - $this->assertEquals('Google', $results[2]->getName()); - - $this->assertInstanceOf(ClientData::class, $results[3]); - $this->assertEquals('Microsoft', $results[3]->getName()); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetById() - { - $client = self::$service->getById(1); - - $this->assertEquals('Google', $client->getName()); - $this->assertEquals('Google Inc.', $client->getDescription()); - - $client = self::$service->getById(2); - - $this->assertEquals('Apple', $client->getName()); - $this->assertEquals('Apple Inc.', $client->getDescription()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getById(10); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllForUserAdmin() - { - $this->assertCount(4, self::$service->getAllForUser()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllForUser() - { - $userData = new UserLoginResponse(); - $userData->setId(4); - - self::$setupUser->call($this, $userData); - - $this->assertCount(2, self::$service->getAllForUser()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - * @throws DuplicatedItemException - */ - public function testCreate() - { - $data = new ClientData(); - $data->name = 'Cliente prueba'; - $data->description = 'Descripción prueba'; - $data->isGlobal = 1; - - $id = self::$service->create($data); - - // Comprobar que el Id devuelto corresponde con el cliente creado - $result = self::$service->getById($id); - - $this->assertEquals($data->name, $result->getName()); - $this->assertEquals($data->isGlobal, $result->getIsGlobal()); - - $countAfter = self::getRowCount('Client'); - - $this->assertEquals(5, $countAfter); - - $this->expectException(DuplicatedItemException::class); - - self::$service->create($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testDeleteByIdBatch() - { - $countBefore = self::getRowCount('Client'); - - self::$service->deleteByIdBatch([4]); - - $countAfter = self::getRowCount('Client'); - - $this->assertEquals($countBefore - 1, $countAfter); - - // Comprobar que se produce una excepción al tratar de eliminar clientes usados - $this->expectException(ConstraintException::class); - - self::$service->deleteByIdBatch([1, 2]); - - $this->expectException(ServiceException::class); - - self::$service->deleteByIdBatch([10]); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetByName() - { - $data = self::$service->getByName('Google'); - - $this->assertEquals(1, $data->getId()); - $this->assertEquals('Google Inc.', $data->getDescription()); - - $data = self::$service->getByName('Apple'); - - $this->assertEquals(2, $data->getId()); - $this->assertEquals('Apple Inc.', $data->getDescription()); - - // Se comprueba que el hash generado es el mismo en para el nombre 'Web' - $data = self::$service->getByName(' google. '); - - $this->assertEquals(1, $data->getId()); - $this->assertEquals('Google Inc.', $data->getDescription()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getByName('Spotify'); - } - - /** - * @throws SPException - */ - public function testDelete() - { - $countBefore = self::getRowCount('Client'); - - self::$service->delete(4); - - $countAfter = self::getRowCount('Client'); - - $this->assertEquals($countBefore - 1, $countAfter); - - // Comprobar que se produce una excepción al tratar de eliminar clientes usados - $this->expectException(ConstraintException::class); - - self::$service->delete(2); - - $this->expectException(NoSuchItemException::class); - - self::$service->delete(10); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdate() - { - $data = new ClientData(); - $data->id = 1; - $data->name = 'Cliente prueba'; - $data->description = 'Descripción cliente prueba'; - - self::$service->update($data); - - $result = self::$service->getById(1); - - $this->assertEquals($data->name, $result->getName()); - $this->assertEquals($data->description, $result->getDescription()); - - // Comprobar la a actualización con un nombre duplicado comprobando su hash - $data = new ClientData(); - $data->id = 1; - $data->name = ' apple.'; - - $this->expectException(DuplicatedItemException::class); - - self::$service->update($data); - } -} diff --git a/tests/SPT/Services/Config/ConfigBackupServiceTest.php b/tests/SPT/Services/Config/ConfigBackupServiceTest.php deleted file mode 100644 index 80fc3c85..00000000 --- a/tests/SPT/Services/Config/ConfigBackupServiceTest.php +++ /dev/null @@ -1,111 +0,0 @@ -. - */ - -namespace SPT\Services\Config; - -use DI\DependencyException; -use DI\NotFoundException; -use PHPUnit\Framework\TestCase; -use SP\Core\Context\ContextException; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Config\Adapters\ConfigData; -use SP\Domain\Config\Ports\ConfigDataInterface; -use SP\Domain\Config\Services\ConfigBackupService; -use SP\Domain\Config\Services\ConfigFileService; -use SP\Infrastructure\File\FileException; - -use function SPT\getResource; -use function SPT\recreateDir; -use function SPT\saveResource; -use function SPT\setupContext; - -/** - * Class ConfigBackupServiceTest - * - * @package SPT\Services\Config - */ -class ConfigBackupServiceTest extends TestCase -{ - protected static $currentConfig; - - public static function setUpBeforeClass(): void - { - self::$currentConfig = getResource('config', 'config.xml'); - } - - /** - * This method is called after the last test of this test class is run. - */ - public static function tearDownAfterClass(): void - { - saveResource('config', 'config.xml', self::$currentConfig); - recreateDir(CACHE_PATH); - } - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public function testBackup() - { - $dic = setupContext(); - - $configData = new ConfigData(); - $configData->setConfigVersion(uniqid()); - - $service = $dic->get(ConfigBackupService::class); - $service->backup($configData); - - $this->assertTrue(true); - - return $configData; - } - - /** - * @depends testBackup - * - * @param ConfigDataInterface $configData - * - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - * @throws ServiceException - * @throws FileException - */ - public function testRestore(ConfigDataInterface $configData) - { - $dic = setupContext(); - - $service = $dic->get(ConfigBackupService::class); - $data = $service->restore(); - - $this->assertEquals($configData->getConfigVersion(), $data->getConfigVersion()); - - $config = $dic->get(ConfigFileService::class)->loadConfigFromFile(); - - $this->assertEquals($config->getConfigVersion(), $data->getConfigVersion()); - $this->assertGreaterThanOrEqual($config->getConfigDate(), $data->getConfigDate()); - } -} diff --git a/tests/SPT/Services/Config/ConfigServiceTest.php b/tests/SPT/Services/Config/ConfigServiceTest.php deleted file mode 100644 index 2350bb4f..00000000 --- a/tests/SPT/Services/Config/ConfigServiceTest.php +++ /dev/null @@ -1,155 +0,0 @@ -. - */ - -namespace SPT\Services\Config; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ConfigData; -use SP\DataModel\Dto\ConfigRequest; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Config\Ports\ConfigServiceInterface; -use SP\Domain\Config\Services\ConfigService; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class ConfigServiceTest - * - * @package SPT\Services\Config - */ -class ConfigServiceTest extends DatabaseTestCase -{ - /** - * @var ConfigServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$service = $dic->get(ConfigService::class); - - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $data = self::$service->getAll(); - - $this->assertCount(self::getRowCount('Config'), $data); - - $this->assertEquals('config_backup', $data[0]->parameter); - $this->assertEquals('789ca558db6edb3810edb718c5be6c6b88ba4b45814de3a497a48d374e832cb0404191944d589654916a9216f9f71d5292633ba1a4621f628bf11cce68e6cc85bc886d2b9e2ce6ff1e1779ca97edd70c4b3c89c328fe2562c78e272f9e13785197cb0a5376c6ee276f440cdba82f273089d3625ddff2353fc97192313a79c3634b019c21c0d72afb2d0520ff0e0bb68b7107318255bf059863217601d110e00bde305162b2675768426514973396e23a93efaba22e95b710205c6b04625e1529cf588731bf4c591577f7a3e3a1a517acfab1ef2ad42b3f2f2aa9b60eadd01a963e0cc3c0de0731307ab3ac938ce76bf119df5d73762b94414e2f977610577ca35de95bd628c88e3ffbbd8f0929ea5c1eab0fada0d7fbadf439a818de9aac18597f2d29964c6c03db2f9d1792931d6963da13fdf8018bd5a42524b6701a440125a1635386b01721124436b27c9fb1d0775ddb4d9dc8f394bc6d0c124d3e14422a1904968a7b4816215ed3e435653f74788dd4a7c9a2206b2677b8d0a74665a29209b65a86101dd1901f4f2e681cf0facbf787e4e5d9fd59fc6b08db515a6145f9cd4b506061d7717c8cc9a0de36791cc752e4b0cda58f25f5724445659be230dd8dea550911475956dc327a7227c101384661fcabc5c593f9ec74cbc478f269fe5eadec66f5fee3e936c940f28bfecd6d5617b32bb5f2bad5624bfe7832bb3856ab40314baf6e74f1687ebc39d7a251bb5a9c6bf5ad35d78b995eb6e65cdd6825a8b5e77871ad97ad41ef8ecef4b2b5e87236d7cbd6a4b3937ff4b2b5e9f8b2d92a68f57e06bd0f633db7e03f9b426cd96e6f126ad0e8dab1cc8a04670b862bb2da86d2582d792e24ce7637ee6d235df7b481b294bc55ac41afe021ad18e325568f45b5ecef937a1f9ed38efe1e70b7e6f42da61b9ebf22f9db1a7e10eaa12d6ce2d5ff55d56529b4e205231593c87634d2eb43ce9feb3bc60c5288830cb28dad5f091f51311c1f25d8b6f9471b8c0558493fb6611b76054f4db5eba6addfa6a39ca6de1a4b598dd35a2c0fd9697e1f90fdc1f2a666d85dc900064054a0254dbb1d2030ca8e69934fc6eab6c13c3baae58a8d9d5414e0d05823e395f069556cba220d2d53fed53686ad1f7bd1dbf600cefbe3d3cbdbb5fc13fdbd621723906d81b755e5718dfe54a297ec7b0d9689c3fa6d8cb002411ed41597f7a322dc003a5e2957a8ff4c7fcb15bbddee5947fafdef4878c93be2a08e38cf6ff630f42e8f14dceeb44fb83efee412d8961336ec6765d16d51d105cef404e28383528a2c2f24d84a129c467e40ad10852ea3b6cd984d42eaf98107bf92089e228252db09e02f85f19da6fd6eaa9880095f1c89635ced9416a3bc6042f02257436c51cba6253683ac318e824b768e731d2f7030cbfb4771257eb562cd4c851cc51ac92a8eb3d74956b3fe02dccc92d7d009c0c62e851ccb9aa2d0f21c64a181131f7c24d0ac86363006fab9f3a891534af894677264ab684e894b56ef1f5f8dbe50f24d433f400c4ce2f0d84c18f0be8ee7f8be1a795c23a83ba67cdc806d8745d2f8320926ebbafcb6da99fa49845c3b0ac324a211c28e2274e83861905a5ee49000239be1d4c376bf97d85d0935707f633742294e08248b150528f1121b411e3976e0fbd8713d0b0784fa76d2dfe05652964f8aa5d1f95059f61b9cd55b901bf14b68b9928d2ec80de8e901da18aa06d0f5084f4fabe60b80768e52cde8aad0d11d6e940d8316b8b508dca3e7b3fe12c47252dd9772d15496edcdc4d039f7b4ce323de41c1138678a2de78c633486960fa32827072c758df5608b8069a1382f963c3f24f8307456a8ea3feac24988e2b93b1af35dd023e0e08ac69caeadf34eee4a5e3d4957a3a23d547781812cc70f2d28fe0fff0152be6bea', $data[0]->value); - } - - /** - * @throws NoSuchItemException - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteByParam() - { - self::$service->deleteByParam('tempmaster_passtime'); - - $this->expectException(NoSuchItemException::class); - - self::$service->deleteByParam('test'); - } - - /** - * @throws ServiceException - */ - public function testSaveBatch() - { - $request = new ConfigRequest(); - $request->add('tempmaster_attempts', 4); - $request->add('tempmaster_maxtime', time()); - $request->add('tempmaster_passtime', time()); - $request->add('test', uniqid()); - - self::$service->saveBatch($request); - - $this->assertTrue(true); - } - - /** - * @throws NoSuchItemException - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testSave() - { - $data = uniqid(); - self::$service->save('test', $data); - - $this->assertEquals($data, self::$service->getByParam('test')); - } - - /** - * @throws NoSuchItemException - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testCreate() - { - $data = new ConfigData('test', uniqid()); - - $this->assertEquals(1, self::$service->create($data)); - - $this->assertEquals($data->getValue(), self::$service->getByParam($data->getParameter())); - } - - /** - * @throws NoSuchItemException - * @throws ServiceException - */ - public function testGetByParam() - { - $this->assertEquals('1531353681', self::$service->getByParam('config_backup_date')); - - $this->expectException(NoSuchItemException::class); - - self::$service->getByParam('test'); - } -} diff --git a/tests/SPT/Services/Crypt/MasterPassServiceTest.php b/tests/SPT/Services/Crypt/MasterPassServiceTest.php deleted file mode 100644 index a97669cb..00000000 --- a/tests/SPT/Services/Crypt/MasterPassServiceTest.php +++ /dev/null @@ -1,202 +0,0 @@ -. - */ - -namespace SPT\Services\Crypt; - -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; -use Exception; -use SP\Core\Context\ContextException; -use SP\Core\Crypt\Crypt; -use SP\Domain\Account\Ports\AccountServiceInterface; -use SP\Domain\Account\Services\AccountService; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Crypt\Ports\MasterPassServiceInterface; -use SP\Domain\Crypt\Services\MasterPassService; -use SP\Domain\Crypt\Services\UpdateMasterPassRequest; -use SP\Domain\CustomField\Ports\CustomFieldServiceInterface; -use SP\Domain\CustomField\Services\CustomFieldService; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; -use SPT\Services\Account\AccountCryptServiceTest; - -use function SPT\setupContext; - -/** - * Class MasterPassServiceTest - * - * @package SPT\Services - */ -class MasterPassServiceTest extends DatabaseTestCase -{ - /** - * @var CustomFieldServiceInterface - */ - private static $customFieldService; - /** - * @var AccountServiceInterface - */ - private static $accountService; - /** - * @var MasterPassServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$service = $dic->get(MasterPassService::class); - self::$accountService = $dic->get(AccountService::class); - self::$customFieldService = $dic->get(CustomFieldService::class); - } - - /** - * @throws CryptoException - * @throws Exception - */ - public function testChangeMasterPassword() - { - $request = new UpdateMasterPassRequest(AccountCryptServiceTest::CURRENT_MASTERPASS, AccountCryptServiceTest::NEW_MASTERPASS, AccountCryptServiceTest::CURRENT_HASH); - - self::$service->changeMasterPassword($request); - - $this->checckAccounts($request); - $this->checkAccountsHistory($request); - $this->checkCustomFields(); - - $this->assertTrue(self::$service->checkMasterPassword(AccountCryptServiceTest::NEW_MASTERPASS)); - - $this->assertTrue(self::$service->checkUserUpdateMPass(time())); - $this->assertFalse(self::$service->checkUserUpdateMPass(time() - 10)); - } - - /** - * @param UpdateMasterPassRequest $request - * - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - private function checckAccounts(UpdateMasterPassRequest $request) - { - $account = self::$accountService->getPasswordForId(1); - $pass = Crypt::decrypt($account->getPass(), $account->getKey(), $request->getNewMasterPass()); - - $this->assertEquals('&¿\'f!i$XwSwc', $pass); - - $account = self::$accountService->getPasswordForId(2); - $pass = Crypt::decrypt($account->getPass(), $account->getKey(), $request->getNewMasterPass()); - - $this->assertEquals('&¿\'f!i$XwSwc', $pass); - } - - /** - * @param UpdateMasterPassRequest $request - * - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - private function checkAccountsHistory(UpdateMasterPassRequest $request) - { - // Verify accounts' password history data - $account = self::$accountService->getPasswordHistoryForId(3); - $pass = Crypt::decrypt($account->getPass(), $account->getKey(), $request->getNewMasterPass()); - - $this->assertEquals($request->getHash(), $account->getMPassHash()); - $this->assertEquals('_{/uHL\>\'Oj0', $pass); - - $account = self::$accountService->getPasswordHistoryForId(4); - $pass = Crypt::decrypt($account->getPass(), $account->getKey(), $request->getNewMasterPass()); - - $this->assertEquals($request->getHash(), $account->getMPassHash()); - $this->assertEquals('-{?^··\mjCgetPasswordHistoryForId(5); - $pass = Crypt::decrypt($account->getPass(), $account->getKey(), $request->getNewMasterPass()); - - $this->assertEquals($request->getHash(), $account->getMPassHash()); - $this->assertEquals('-{?^··\mjCgetPasswordHistoryForId(6); - $pass = Crypt::decrypt($account->getPass(), $account->getKey(), $request->getNewMasterPass()); - - $this->assertEquals($request->getHash(), $account->getMPassHash()); - $this->assertEquals('-{?^··\mjCgetPasswordHistoryForId(7); - $pass = Crypt::decrypt($account->getPass(), $account->getKey(), $request->getNewMasterPass()); - - $this->assertEquals($request->getHash(), $account->getMPassHash()); - $this->assertEquals('-{?^··\mjCgetAllEncrypted(); - - $data = Crypt::decrypt($result[0]->getData(), $result[0]->getKey(), AccountCryptServiceTest::NEW_MASTERPASS); - - $this->assertEquals('1234', $data); - } - - /** - * @throws NoSuchItemException - * @throws ServiceException - */ - public function testCheckUserUpdateMPass() - { - $this->assertTrue(self::$service->checkUserUpdateMPass(time())); - $this->assertFalse(self::$service->checkUserUpdateMPass(1528236611 - 10)); - } - - /** - * @throws NoSuchItemException - * @throws ServiceException - */ - public function testCheckMasterPassword() - { - $this->assertTrue(self::$service->checkMasterPassword(AccountCryptServiceTest::CURRENT_MASTERPASS)); - $this->assertFalse(self::$service->checkMasterPassword(AccountCryptServiceTest::NEW_MASTERPASS)); - } -} diff --git a/tests/SPT/Services/Crypt/TemporaryMasterPassServiceTest.php b/tests/SPT/Services/Crypt/TemporaryMasterPassServiceTest.php deleted file mode 100644 index c27323d4..00000000 --- a/tests/SPT/Services/Crypt/TemporaryMasterPassServiceTest.php +++ /dev/null @@ -1,134 +0,0 @@ -. - */ - -namespace SPT\Services\Crypt; - -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; -use PHPUnit\Framework\TestCase; -use SP\Core\Context\ContextException; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Context\ContextInterface; -use SP\Domain\Crypt\Ports\TemporaryMasterPassServiceInterface; -use SP\Domain\Crypt\Services\TemporaryMasterPassService; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; - -use function SPT\setupContext; - -/** - * Class TemporaryMasterPassServiceTest - * - * @package SPT\Services\Crypt - */ -class TemporaryMasterPassServiceTest extends TestCase -{ - /** - * @var ContextInterface - */ - private $context; - /** - * @var TemporaryMasterPassServiceInterface - */ - private $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public function setUp(): void - { - $dic = setupContext(); - - // Inicializar el repositorio - $this->service = $dic->get(TemporaryMasterPassService::class); - - $this->context = $dic->get(ContextInterface::class); - } - - /** - * @throws ServiceException - */ - public function testCreate() - { - $key = $this->service->create(); - - $this->assertNotEmpty($key); - $this->assertEquals($this->context->getTrasientKey('_tempmasterpass'), $key); - - return $key; - } - - /** - * @depends testCreate - * - * @param $key - * - * @throws CryptoException - * @throws NoSuchItemException - * @throws ServiceException - */ - public function testGetUsingKey($key) - { - $this->assertEquals('12345678900', $this->service->getUsingKey($key)); - - $this->expectException(CryptoException::class); - - $this->service->getUsingKey('test123'); - } - - /** - * @depends testCreate - * - * @param $key - * - * @throws ServiceException - */ - public function testCheckTempMasterPass($key) - { - $this->assertTrue($this->service->checkTempMasterPass($key)); - - for ($i = 1; $i <= 50; $i++) { - $this->assertFalse($this->service->checkTempMasterPass('test123')); - } - - // The 50's attempt should fails - $this->assertFalse($this->service->checkTempMasterPass($key)); - } - - /** - * @throws ServiceException - */ - public function testExpiredKey() - { - $key = $this->service->create(10); - - print 'Sleeping for 12 seconds'; - - sleep(12); - - $this->assertFalse($this->service->checkTempMasterPass($key)); - } -} diff --git a/tests/SPT/Services/CustomField/CustomFieldCryptServiceTest.php b/tests/SPT/Services/CustomField/CustomFieldCryptServiceTest.php deleted file mode 100644 index f59c2dea..00000000 --- a/tests/SPT/Services/CustomField/CustomFieldCryptServiceTest.php +++ /dev/null @@ -1,95 +0,0 @@ -. - */ - -namespace SPT\Services\CustomField; - -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Core\Crypt\Crypt; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Crypt\Services\UpdateMasterPassRequest; -use SP\Domain\CustomField\Ports\CustomFieldCryptServiceInterface; -use SP\Domain\CustomField\Ports\CustomFieldServiceInterface; -use SP\Domain\CustomField\Services\CustomFieldCryptService; -use SP\Domain\CustomField\Services\CustomFieldService; -use SPT\DatabaseTestCase; -use SPT\Services\Account\AccountCryptServiceTest; - -use function SPT\setupContext; - -/** - * Class CustomFieldCryptServiceTest - * - * @package SPT\Services\CustomField - */ -class CustomFieldCryptServiceTest extends DatabaseTestCase -{ - /** - * @var CustomFieldServiceInterface - */ - private static $customFieldService; - /** - * @var CustomFieldCryptServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$service = $dic->get(CustomFieldCryptService::class); - self::$customFieldService = $dic->get(CustomFieldService::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - * @throws CryptoException - */ - public function testUpdateMasterPassword() - { - $request = new UpdateMasterPassRequest(AccountCryptServiceTest::CURRENT_MASTERPASS, AccountCryptServiceTest::NEW_MASTERPASS, AccountCryptServiceTest::CURRENT_HASH); - - self::$service->updateMasterPassword($request); - - $result = self::$customFieldService->getAllEncrypted(); - - $data = Crypt::decrypt($result[0]->getData(), $result[0]->getKey(), AccountCryptServiceTest::NEW_MASTERPASS); - - $this->assertEquals('1234', $data); - } -} diff --git a/tests/SPT/Services/CustomField/CustomFieldDefServiceTest.php b/tests/SPT/Services/CustomField/CustomFieldDefServiceTest.php deleted file mode 100644 index 0f7c71fc..00000000 --- a/tests/SPT/Services/CustomField/CustomFieldDefServiceTest.php +++ /dev/null @@ -1,251 +0,0 @@ -. - */ - -namespace SPT\Services\CustomField; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\CustomFieldDefinitionData; -use SP\DataModel\ItemSearchData; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Acl\AclActionsInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\CustomField\Services\CustomFieldDefService; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class CustomFieldDefServiceTest - * - * @package SPT\Services\CustomField - */ -class CustomFieldDefServiceTest extends DatabaseTestCase -{ - /** - * @var CustomFieldDefService - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$service = $dic->get(CustomFieldDefService::class); - } - - /** - * @throws ServiceException - */ - public function testDelete() - { - self::$service->delete(3); - - $this->expectException(NoSuchItemException::class); - - self::$service->delete(10); - - $this->expectException(ConstraintException::class); - - self::$service->delete(1); - - $this->assertEquals(2, self::getRowCount('CustomFieldDefinition')); - $this->assertEquals(3, self::getRowCount('CustomFieldData')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllBasic() - { - $data = self::$service->getAllBasic(); - - $this->assertCount(3, $data); - - $expected = new CustomFieldDefinitionData(); - $expected->setId(1); - $expected->setName('Prueba'); - $expected->setIsEncrypted(1); - $expected->setHelp('Ayuda'); - $expected->setModuleId(AclActionsInterface::ACCOUNT); - $expected->setRequired(true); - $expected->setTypeId(1); - $expected->setShowInList(0); - - $this->assertEquals($expected, $data[0]); - - $expected = new CustomFieldDefinitionData(); - $expected->setId(2); - $expected->setName('RSA'); - $expected->setIsEncrypted(0); - $expected->setModuleId(AclActionsInterface::CATEGORY); - $expected->setRequired(false); - $expected->setTypeId(2); - $expected->setShowInList(0); - - $this->assertEquals($expected, $data[1]); - } - - /** - * @throws ServiceException - */ - public function testDeleteByIdBatch() - { - self::$service->deleteByIdBatch([3]); - - self::$service->deleteByIdBatch([]); - - $this->expectException(ServiceException::class); - - self::$service->deleteByIdBatch([3, 4]); - - $this->expectException(ConstraintException::class); - - self::$service->deleteByIdBatch([1, 2]); - - $this->assertEquals(2, self::getRowCount('CustomFieldDefinition')); - $this->assertEquals(3, self::getRowCount('CustomFieldData')); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testCreate() - { - $data = new CustomFieldDefinitionData(); - $data->setId(4); - $data->setName('Phone'); - $data->setIsEncrypted(0); - $data->setHelp('Telefono'); - $data->setModuleId(AclActionsInterface::ACCOUNT); - $data->setRequired(true); - $data->setTypeId(6); - $data->setShowInList(0); - - $this->assertEquals(4, self::$service->create($data)); - - $this->assertEquals(4, self::getRowCount('CustomFieldDefinition')); - - $this->assertEquals($data, self::$service->getById(4)); - - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetById() - { - $expected = new CustomFieldDefinitionData(); - $expected->setId(1); - $expected->setName('Prueba'); - $expected->setIsEncrypted(1); - $expected->setHelp('Ayuda'); - $expected->setModuleId(AclActionsInterface::ACCOUNT); - $expected->setRequired(true); - $expected->setTypeId(1); - $expected->setShowInList(0); - - $this->assertEquals($expected, self::$service->getById(1)); - - $this->expectException(NoSuchItemException::class); - - $this->assertEquals($expected, self::$service->getById(10)); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - * @throws ServiceException - */ - public function testUpdate() - { - $data = new CustomFieldDefinitionData(); - $data->setId(1); - $data->setName('PIN'); - $data->setIsEncrypted(0); - $data->setHelp('Pin code'); - $data->setModuleId(AclActionsInterface::CLIENT); - $data->setRequired(false); - $data->setTypeId(2); - $data->setShowInList(1); - - self::$service->update($data); - - $dataUpdated = self::$service->getById(1); - - $this->assertEquals($data, $dataUpdated); - - $this->assertEquals(1, self::getRowCount('CustomFieldData')); - - $data->setTypeId(100); - - $this->expectException(ConstraintException::class); - - $this->assertEquals(1, self::$service->update($data)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setSeachString('RSA'); - $itemSearchData->setLimitCount(10); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertEquals(1, $result->getTotalNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(CustomFieldDefinitionData::class, $data[0]); - $this->assertEquals(2, $data[0]->id); - $this->assertEquals('password', $data[0]->typeName); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setSeachString('test'); - $itemSearchData->setLimitCount(10); - - $this->assertEquals(0, self::$service->search($itemSearchData)->getNumRows()); - } -} diff --git a/tests/SPT/Services/CustomField/CustomFieldServiceTest.php b/tests/SPT/Services/CustomField/CustomFieldServiceTest.php deleted file mode 100644 index 3523fe04..00000000 --- a/tests/SPT/Services/CustomField/CustomFieldServiceTest.php +++ /dev/null @@ -1,403 +0,0 @@ -. - */ - -namespace SPT\Services\CustomField; - -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Core\Crypt\Crypt; -use SP\DataModel\CustomFieldData; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Acl\AclActionsInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\CustomField\Ports\CustomFieldServiceInterface; -use SP\Domain\CustomField\Services\CustomFieldService; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; -use SPT\Services\Account\AccountCryptServiceTest; - -use function SPT\setupContext; - -/** - * Class CustomFieldServiceTest - * - * @package SPT\Services\CustomField - */ -class CustomFieldServiceTest extends DatabaseTestCase -{ - /** - * @var CustomFieldServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el repositorio - self::$service = $dic->get(CustomFieldService::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteCustomFieldDefinitionDataBatch() - { - $this->assertEquals(3, self::$service->deleteCustomFieldDefinitionDataBatch([1, 2, 3])); - - $this->assertEquals(0, self::getRowCount('CustomFieldData')); - - $this->assertEquals(0, self::$service->deleteCustomFieldDefinitionDataBatch([])); - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testUpdateMasterPass() - { - $customFields = self::$service->getAllEncrypted(); - - foreach ($customFields as $customField) { - $data = Crypt::decrypt( - $customField->getData(), - $customField->getKey(), - AccountCryptServiceTest::CURRENT_MASTERPASS); - - $customField->setData($data); - - $this->assertEquals(1, self::$service->updateMasterPass($customField, AccountCryptServiceTest::NEW_MASTERPASS)); - } - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllEncrypted() - { - $data = self::$service->getAllEncrypted(); - - $this->assertCount(2, $data); - $this->assertEquals(1, $data[0]->getDefinitionId()); - $this->assertEquals(1, $data[0]->getItemId()); - $this->assertEquals(1, $data[1]->getDefinitionId()); - $this->assertEquals(2, $data[1]->getItemId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteCustomFieldDataBatch() - { - $this->assertEquals(2, self::$service->deleteCustomFieldDataBatch([1, 2, 3], AclActionsInterface::ACCOUNT)); - - $this->assertEquals(1, self::$service->deleteCustomFieldDataBatch([1, 2, 3], AclActionsInterface::CATEGORY)); - - $this->assertEquals(0, self::getRowCount('CustomFieldData')); - - $this->assertEquals(0, self::$service->deleteCustomFieldDataBatch([], AclActionsInterface::CATEGORY)); - - $this->assertEquals(0, self::$service->deleteCustomFieldDataBatch([], AclActionsInterface::USER)); - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdateOrCreateData() - { - $data = new CustomFieldData(); - $data->setItemId(1); - $data->setModuleId(AclActionsInterface::ACCOUNT); - $data->setDefinitionId(1); - $data->setData('cuenta'); - - $this->assertTrue(self::$service->updateOrCreateData($data)); - - $data = new CustomFieldData(); - $data->setItemId(1); - $data->setModuleId(AclActionsInterface::CATEGORY); - $data->setDefinitionId(2); - $data->setData('categoria'); - - $this->assertTrue(self::$service->updateOrCreateData($data)); - - $data = new CustomFieldData(); - $data->setItemId(2); - $data->setModuleId(AclActionsInterface::ACCOUNT); - $data->setDefinitionId(1); - $data->setData('cuenta'); - - $this->assertTrue(self::$service->updateOrCreateData($data)); - - $data = new CustomFieldData(); - $data->setItemId(2); - $data->setModuleId(AclActionsInterface::CATEGORY); - $data->setDefinitionId(2); - $data->setData('categoria'); - - $this->assertTrue(self::$service->updateOrCreateData($data)); - - $this->assertTrue(self::$service->updateOrCreateData(new CustomFieldData())); - - $data = new CustomFieldData(); - $data->setItemId(2); - $data->setModuleId(AclActionsInterface::USER); - $data->setDefinitionId(3); - $data->setData('nan'); - - $this->assertEquals(true, self::$service->updateOrCreateData($data)); - - $this->assertEquals(5, self::getRowCount('CustomFieldData')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetForModuleAndItemId() - { - $result = self::$service->getForModuleAndItemId(AclActionsInterface::ACCOUNT, 1); - - $this->assertCount(1, $result); - $this->assertEquals('Prueba', $result[0]->definitionName); - $this->assertEquals(1, $result[0]->definitionId); - $this->assertEquals(AclActionsInterface::ACCOUNT, $result[0]->moduleId); - $this->assertEquals(1, $result[0]->required); - $this->assertEquals(0, $result[0]->showInList); - $this->assertEquals('Ayuda', $result[0]->help); - $this->assertEquals(1, $result[0]->isEncrypted); - $this->assertEquals(1, $result[0]->typeId); - $this->assertEquals('text', $result[0]->typeName); - $this->assertEquals('Texto', $result[0]->typeText); - $this->assertNotEmpty($result[0]->data); - $this->assertNotEmpty($result[0]->key); - - $result = self::$service->getForModuleAndItemId(AclActionsInterface::ACCOUNT, 2); - - $this->assertCount(1, $result); - $this->assertEquals('Prueba', $result[0]->definitionName); - $this->assertEquals(1, $result[0]->definitionId); - $this->assertEquals(AclActionsInterface::ACCOUNT, $result[0]->moduleId); - $this->assertEquals(1, $result[0]->required); - $this->assertEquals(0, $result[0]->showInList); - $this->assertEquals('Ayuda', $result[0]->help); - $this->assertEquals(1, $result[0]->isEncrypted); - $this->assertEquals(1, $result[0]->typeId); - $this->assertEquals('text', $result[0]->typeName); - $this->assertEquals('Texto', $result[0]->typeText); - $this->assertNotEmpty($result[0]->data); - $this->assertNotEmpty($result[0]->key); - - $result = self::$service->getForModuleAndItemId(AclActionsInterface::ACCOUNT, 3); - - $this->assertCount(1, $result); - - $result = self::$service->getForModuleAndItemId(AclActionsInterface::CATEGORY, 1); - - $this->assertCount(2, $result); - $this->assertEquals('SSL', $result[0]->definitionName); - $this->assertEquals(3, $result[0]->definitionId); - $this->assertEquals(AclActionsInterface::CATEGORY, $result[0]->moduleId); - $this->assertEquals(0, $result[0]->required); - $this->assertEquals(0, $result[0]->showInList); - $this->assertEquals(null, $result[0]->help); - $this->assertEquals(1, $result[0]->isEncrypted); - $this->assertEquals(10, $result[0]->typeId); - $this->assertEquals('textarea', $result[0]->typeName); - $this->assertEquals('Área de Texto', $result[0]->typeText); - $this->assertNull($result[0]->data); - $this->assertNull($result[0]->key); - - $this->assertEquals('RSA', $result[1]->definitionName); - $this->assertEquals(2, $result[1]->definitionId); - $this->assertEquals(AclActionsInterface::CATEGORY, $result[1]->moduleId); - $this->assertEquals(0, $result[1]->required); - $this->assertEquals(0, $result[1]->showInList); - $this->assertEquals(null, $result[1]->help); - $this->assertEquals(0, $result[1]->isEncrypted); - $this->assertEquals(2, $result[1]->typeId); - $this->assertEquals('password', $result[1]->typeName); - $this->assertEquals('Clave', $result[1]->typeText); - $this->assertNotEmpty($result[1]->data); - $this->assertNull($result[1]->key); - - $result = self::$service->getForModuleAndItemId(AclActionsInterface::CATEGORY, 2); - - $this->assertEquals('SSL', $result[0]->definitionName); - $this->assertEquals(3, $result[0]->definitionId); - $this->assertEquals(AclActionsInterface::CATEGORY, $result[0]->moduleId); - $this->assertEquals(0, $result[0]->required); - $this->assertEquals(0, $result[0]->showInList); - $this->assertEquals(null, $result[0]->help); - $this->assertEquals(1, $result[0]->isEncrypted); - $this->assertEquals(10, $result[0]->typeId); - $this->assertEquals('textarea', $result[0]->typeName); - $this->assertEquals('Área de Texto', $result[0]->typeText); - $this->assertNull($result[0]->data); - $this->assertNull($result[0]->key); - - $this->assertCount(2, $result); - $this->assertEquals('RSA', $result[1]->definitionName); - $this->assertEquals(2, $result[1]->definitionId); - $this->assertEquals(AclActionsInterface::CATEGORY, $result[1]->moduleId); - $this->assertEquals(0, $result[1]->required); - $this->assertEquals(0, $result[1]->showInList); - $this->assertEquals(null, $result[1]->help); - $this->assertEquals(0, $result[1]->isEncrypted); - $this->assertEquals(2, $result[1]->typeId); - $this->assertEquals('password', $result[1]->typeName); - $this->assertEquals('Clave', $result[1]->typeText); - $this->assertNull($result[1]->data); - $this->assertNull($result[1]->key); - - $result = self::$service->getForModuleAndItemId(AclActionsInterface::CATEGORY, 3); - - $this->assertCount(2, $result); - - $result = self::$service->getForModuleAndItemId(AclActionsInterface::USER, 1); - - $this->assertCount(0, $result); - } - - /** - * @throws SPException - */ - public function testDeleteCustomFieldData() - { - $this->assertEquals(1, self::$service->deleteCustomFieldData(1, AclActionsInterface::ACCOUNT)); - $this->assertEquals(1, self::$service->deleteCustomFieldData(2, AclActionsInterface::ACCOUNT)); - $this->assertEquals(1, self::$service->deleteCustomFieldData(1, AclActionsInterface::CATEGORY)); - - $this->assertEquals(0, self::getRowCount('CustomFieldData')); - - $this->assertEquals(0, self::$service->deleteCustomFieldData(2, AclActionsInterface::ACCOUNT)); - - $this->assertEquals(0, self::$service->deleteCustomFieldData(2, AclActionsInterface::CATEGORY)); - - $this->assertEquals(0, self::$service->deleteCustomFieldData(2, AclActionsInterface::USER)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteCustomFieldDefinitionData() - { - $this->assertEquals(2, self::$service->deleteCustomFieldDefinitionData(1)); - $this->assertEquals(1, self::$service->deleteCustomFieldDefinitionData(2)); - $this->assertEquals(0, self::$service->deleteCustomFieldDefinitionData(3)); - - $this->assertEquals(0, self::getRowCount('CustomFieldData')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $result = self::$service->getAll(); - - $this->assertCount(3, $result); - $this->assertInstanceOf(CustomFieldData::class, $result[0]); - $this->assertInstanceOf(CustomFieldData::class, $result[1]); - } - - /** - * @throws ConstraintException - * @throws CryptoException - * @throws QueryException - * @throws NoSuchItemException - * @throws ServiceException - */ - public function testCreate() - { - $data = new CustomFieldData(); - $data->setId(2); - $data->setModuleId(AclActionsInterface::ACCOUNT); - $data->setDefinitionId(1); - $data->setData('cuenta'); - $data->setKey('nan'); - - $this->assertEquals(3, self::$service->create($data)); - - $data = new CustomFieldData(); - $data->setId(2); - $data->setModuleId(AclActionsInterface::CATEGORY); - $data->setDefinitionId(2); - $data->setData('categoria'); - $data->setKey('nan'); - - $this->assertEquals(4, self::$service->create($data)); - - $this->expectException(NoSuchItemException::class); - - $data = new CustomFieldData(); - $data->setId(2); - $data->setModuleId(AclActionsInterface::ACCOUNT); - $data->setDefinitionId(1); - $data->setData('cuenta'); - $data->setKey('nan'); - - self::$service->create($data); - - $data->setDefinitionId(3); - - self::$service->create($data); - - $data = new CustomFieldData(); - $data->setId(2); - $data->setModuleId(AclActionsInterface::CATEGORY); - $data->setDefinitionId(2); - $data->setData('categoria'); - $data->setKey('nan'); - - self::$service->create($data); - - $data->setDefinitionId(4); - - self::$service->create($data); - - $this->assertEquals(4, self::getRowCount('CustomFieldData')); - } -} diff --git a/tests/SPT/Services/Eventlog/EventlogServiceTest.php b/tests/SPT/Services/Eventlog/EventlogServiceTest.php deleted file mode 100644 index c7788b93..00000000 --- a/tests/SPT/Services/Eventlog/EventlogServiceTest.php +++ /dev/null @@ -1,151 +0,0 @@ -. - */ - -namespace SPT\Services\Eventlog; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\EventlogData; -use SP\DataModel\ItemSearchData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\Security\Ports\EventlogServiceInterface; -use SP\Domain\Security\Services\EventlogService; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class EventlogServiceTest - * - * @package SPT\Services\Eventlog - */ -class EventlogServiceTest extends DatabaseTestCase -{ - /** - * @var EventlogServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(EventlogService::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testClear() - { - self::$service->clear(); - - $this->assertEquals(0, self::getRowCount('EventLog')); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('login.auth.database'); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(4, $result->getNumRows()); - $this->assertCount(4, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals('login.auth.database', $data[0]->action); - - $itemSearchData->setSeachString('login.auth.'); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(4, $result->getNumRows()); - $this->assertCount(4, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - - $itemSearchData->setSeachString('Tiempo inactivo : 0 min.'); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - - $itemSearchData->setSeachString('prueba'); - - $result = self::$service->search($itemSearchData); - - $this->assertCount(0, $result->getDataAsArray()); - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCreate() - { - $eventlogData = new EventlogData(); - $eventlogData->setAction('test'); - $eventlogData->setLevel('INFO'); - $eventlogData->setUserId(1); - $eventlogData->setLogin('Admin'); - $eventlogData->setIpAddress('127.0.0.1'); - $eventlogData->setDescription('Prueba'); - - $countBefore = self::getRowCount('EventLog'); - - self::$service->create($eventlogData); - - $countAfter = self::getRowCount('EventLog'); - - $this->assertEquals($countBefore + 1, $countAfter); - - $this->expectException(ConstraintException::class); - - self::$service->create(new EventlogData()); - } -} diff --git a/tests/SPT/Services/Export/XmlExportServiceTest.php b/tests/SPT/Services/Export/XmlExportServiceTest.php deleted file mode 100644 index 258d0c32..00000000 --- a/tests/SPT/Services/Export/XmlExportServiceTest.php +++ /dev/null @@ -1,161 +0,0 @@ -. - */ - -namespace SPT\Services\Export; - -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Export\Ports\XmlExportServiceInterface; -use SP\Domain\Export\Ports\XmlVerifyServiceInterface; -use SP\Domain\Export\Services\VerifyResult; -use SP\Domain\Export\Services\XmlExportService; -use SP\Domain\Export\Services\XmlVerifyService; -use SP\Infrastructure\File\FileException; -use SP\Util\PasswordUtil; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class XmlExportServiceTest - * - * @package SPT\Services\Export - */ -class XmlExportServiceTest extends DatabaseTestCase -{ - /** - * @var XmlExportServiceInterface - */ - private static $xmlExportService; - /** - * @var XmlVerifyServiceInterface - */ - private static $xmlVerifyService; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - array_map('unlink', glob(TMP_PATH . DIRECTORY_SEPARATOR . '*.xml')); - - $dic = setupContext(); - - self::$loadFixtures = true; - - self::$xmlExportService = $dic->get(XmlExportService::class); - self::$xmlVerifyService = $dic->get(XmlVerifyService::class); - } - - /** - * @throws ServiceException - * @throws FileException - */ - public function testDoExportWithoutPassword() - { - self::$xmlExportService->doExport(TMP_PATH); - - $this->assertFileExists(self::$xmlExportService->getExportFile()); - - $this->verifyExportWithoutPassword(self::$xmlExportService->getExportFile()); - } - - /** - * @depends testDoExportWithoutPassword - * - * @param $file - * - * @throws ServiceException - * @throws FileException - */ - private function verifyExportWithoutPassword($file) - { - $result = self::$xmlVerifyService->verify($file); - - $this->assertInstanceOf(VerifyResult::class, $result); - - $this->checkVerifyResult($result); - } - - /** - * @param VerifyResult $verifyResult - */ - private function checkVerifyResult(VerifyResult $verifyResult) - { - $nodes = $verifyResult->getNodes(); - - $this->assertCount(4, $nodes); - $this->assertArrayHasKey('Account', $nodes); - $this->assertArrayHasKey('Category', $nodes); - $this->assertArrayHasKey('Client', $nodes); - $this->assertArrayHasKey('Tag', $nodes); - $this->assertEquals(4, $nodes['Account']); - $this->assertEquals(3, $nodes['Category']); - $this->assertEquals(4, $nodes['Client']); - $this->assertEquals(3, $nodes['Tag']); - } - - /** - * @throws CryptoException - * @throws ServiceException - * @throws FileException - */ - public function testDoExportWithPassword() - { - $password = PasswordUtil::randomPassword(); - - self::$xmlExportService->doExport(TMP_PATH, $password); - - $this->assertFileExists(self::$xmlExportService->getExportFile()); - - $this->verifyExportWithPassword(self::$xmlExportService->getExportFile(), $password); - } - - /** - * @param $file - * @param $password - * - * @throws CryptoException - * @throws ServiceException - * @throws FileException - */ - private function verifyExportWithPassword($file, $password) - { - $result = self::$xmlVerifyService->verifyEncrypted($file, $password); - - $this->assertInstanceOf(VerifyResult::class, $result); - $this->assertTrue($result->isEncrypted()); - - $this->checkVerifyResult($result); - - $this->expectException(ServiceException::class); - - self::$xmlVerifyService->verifyEncrypted($file, 'test123'); - } -} diff --git a/tests/SPT/Services/Export/XmlVerifyServiceTest.php b/tests/SPT/Services/Export/XmlVerifyServiceTest.php deleted file mode 100644 index a210cd7f..00000000 --- a/tests/SPT/Services/Export/XmlVerifyServiceTest.php +++ /dev/null @@ -1,128 +0,0 @@ -. - */ - -namespace SPT\Services\Export; - -use DI\DependencyException; -use DI\NotFoundException; -use DOMDocument; -use PHPUnit\Framework\TestCase; -use SP\Core\Context\ContextException; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Export\Ports\XmlVerifyServiceInterface; -use SP\Domain\Export\Services\VerifyResult; -use SP\Domain\Export\Services\XmlVerifyService; -use SP\Domain\Import\Services\ImportException; -use SP\Infrastructure\File\FileException; - -use function SPT\setupContext; - -/** - * Class XmlVerifyServiceTest - * - * @package SPT\Services\Export - */ -class XmlVerifyServiceTest extends TestCase -{ - /** - * @var XmlVerifyServiceInterface - */ - private static $xmlVerifyService; - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$xmlVerifyService = $dic->get(XmlVerifyService::class); - } - - /** - * @throws FileException - * @throws ImportException - * @throws ServiceException - */ - public function testVerifyEncrypted() - { - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_syspass_encrypted.xml'; - - $result = self::$xmlVerifyService->verifyEncrypted($file, 'test_encrypt'); - - $this->assertInstanceOf(VerifyResult::class, $result); - $this->assertEquals(300.18082201, $result->getVersion()); - - $nodes = $result->getNodes(); - - $this->assertCount(4, $nodes); - $this->assertEquals(4, $nodes['Category']); - $this->assertEquals(3, $nodes['Client']); - $this->assertEquals(6, $nodes['Tag']); - $this->assertEquals(2, $nodes['Account']); - } - - /** - * @throws FileException - * @throws ServiceException - * @throws ImportException - */ - public function testVerify() - { - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_syspass.xml'; - - $result = self::$xmlVerifyService->verify($file); - - $this->assertInstanceOf(VerifyResult::class, $result); - $this->assertEquals(300.18071701, $result->getVersion()); - - $nodes = $result->getNodes(); - - $this->assertCount(4, $nodes); - $this->assertEquals(5, $nodes['Category']); - $this->assertEquals(4, $nodes['Client']); - $this->assertEquals(7, $nodes['Tag']); - $this->assertEquals(5, $nodes['Account']); - } - - public function testCheckXmlHash() - { - $dom = new DOMDocument(); - $dom->load(RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_syspass_encrypted.xml'); - - $this->assertTrue(XmlVerifyService::checkXmlHash($dom, 'test_encrypt')); - - $dom->load(RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_syspass_invalid.xml'); - - $this->assertFalse(XmlVerifyService::checkXmlHash($dom, 'test_encrypt')); - - $key = sha1('d5851082a3914a647a336d8910e24eb64b8f8adef24d27329040ebd0d4c1'); - - $dom->load(RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_syspass_valid_hash.xml'); - - $this->assertTrue(XmlVerifyService::checkXmlHash($dom, $key)); - } -} diff --git a/tests/SPT/Services/Import/CsvImportTest.php b/tests/SPT/Services/Import/CsvImportTest.php deleted file mode 100644 index 6935f42f..00000000 --- a/tests/SPT/Services/Import/CsvImportTest.php +++ /dev/null @@ -1,186 +0,0 @@ -. - */ - -namespace SPT\Services\Import; - -use Defuse\Crypto\Exception\CryptoException; -use DI\Container; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Core\Crypt\Crypt; -use SP\Domain\Account\Services\AccountService; -use SP\Domain\Category\Services\CategoryService; -use SP\Domain\Client\Services\ClientService; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Import\Services\CsvImport; -use SP\Domain\Import\Services\FileImport; -use SP\Domain\Import\Services\ImportException; -use SP\Domain\Import\Services\ImportParams; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SP\Infrastructure\File\FileException; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class CsvImportTest - * - * @package SPT\Services\Import - */ -class CsvImportTest extends DatabaseTestCase -{ - /** - * @var Container - */ - protected static $dic; - - /** - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - self::$dic = setupContext(); - - self::$loadFixtures = true; - } - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - * @throws ImportException - * @throws FileException - */ - public function testDoImport() - { - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data.csv'; - - $params = new ImportParams(); - $params->setDefaultUser(1); - $params->setDefaultGroup(1); - - $import = new CsvImport(self::$dic, FileImport::fromFilesystem($file), $params); - $import->doImport(); - - $this->assertEquals(4, $import->getCounter()); - - $this->checkImportedData(); - } - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - private function checkImportedData() - { - // Checkout categories - $this->assertEquals('CSV Category 1', self::$dic->get(CategoryService::class)->getByName('CSV Category 1')->getName()); - $this->assertEquals(4, self::getRowCount('Category')); - - // Checkout clients - $this->assertEquals('CSV Client 1', self::$dic->get(ClientService::class)->getByName('CSV Client 1')->getName()); - $this->assertEquals(5, self::getRowCount('Client')); - - // Checkout accounts - $accountService = self::$dic->get(AccountService::class); - - // 1st account - $expectedId = 5; - $data = $accountService->getByIdEnriched($expectedId)->getAccountVData(); - - $this->assertEquals($expectedId, $data->getId()); - $this->assertEquals('Test CSV 1', $data->getName()); - $this->assertEquals('CSV Client 1', $data->getClientName()); - $this->assertEquals('CSV Category 1', $data->getCategoryName()); - $this->assertEquals('http://test.me', $data->getUrl()); - $this->assertEquals('CSV Notes', $data->getNotes()); - $this->assertEquals('csv_login1', $data->getLogin()); - - $pass = $accountService->getPasswordForId($data->getId()); - - $this->assertEquals('csv_pass1', Crypt::decrypt($pass->getPass(), $pass->getKey(), '12345678900')); - - // 2nd account - $expectedId = 6; - $data = $accountService->getByIdEnriched($expectedId)->getAccountVData(); - - $this->assertEquals($expectedId, $data->getId()); - $this->assertEquals('Test CSV 2', $data->getName()); - $this->assertEquals('Google', $data->getClientName()); - $this->assertEquals('Linux', $data->getCategoryName()); - $this->assertEquals('http://linux.org', $data->getUrl()); - $this->assertEquals("CSV Notes 2\nbla\nbla\ncar\n", $data->getNotes()); - $this->assertEquals('csv_login2', $data->getLogin()); - - $pass = $accountService->getPasswordForId($data->getId()); - - $this->assertEquals('csv_pass2', Crypt::decrypt($pass->getPass(), $pass->getKey(), '12345678900')); - - // 3rd account - $expectedId = 7; - $data = $accountService->getByIdEnriched($expectedId)->getAccountVData(); - - $this->assertEquals($expectedId, $data->getId()); - $this->assertEquals('Test CSV 3', $data->getName()); - $this->assertEquals('Apple', $data->getClientName()); - $this->assertEquals('SSH', $data->getCategoryName()); - $this->assertEquals('http://apple.com', $data->getUrl()); - $this->assertEquals('CSV Notes 3', $data->getNotes()); - $this->assertEquals('csv_login2', $data->getLogin()); - - $pass = $accountService->getPasswordForId($data->getId()); - - $this->assertEquals('csv_pass3', Crypt::decrypt($pass->getPass(), $pass->getKey(), '12345678900')); - - $this->assertEquals(8, self::getRowCount('Account')); - } - - /** - * @throws ImportException - * @throws FileException - */ - public function testDoImportInvalidData() - { - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_invalid.csv'; - - $params = new ImportParams(); - $params->setDefaultUser(1); - $params->setDefaultGroup(1); - - $import = new CsvImport(self::$dic, FileImport::fromFilesystem($file), $params); - - $this->expectException(ImportException::class); - - $import->doImport(); - } -} diff --git a/tests/SPT/Services/Import/KeepassImportTest.php b/tests/SPT/Services/Import/KeepassImportTest.php deleted file mode 100644 index aa8f04a9..00000000 --- a/tests/SPT/Services/Import/KeepassImportTest.php +++ /dev/null @@ -1,198 +0,0 @@ -. - */ - -namespace SPT\Services\Import; - -use Defuse\Crypto\Exception\CryptoException; -use DI\Container; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Core\Crypt\Crypt; -use SP\DataModel\AccountSearchVData; -use SP\Domain\Account\Search\AccountSearchFilter; -use SP\Domain\Account\Services\AccountService; -use SP\Domain\Category\Services\CategoryService; -use SP\Domain\Client\Services\ClientService; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\Import\Services\FileImport; -use SP\Domain\Import\Services\ImportException; -use SP\Domain\Import\Services\ImportParams; -use SP\Domain\Import\Services\KeepassImport; -use SP\Domain\Import\Services\XmlFileImport; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SP\Infrastructure\File\FileException; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class KeepassImportTest - * - * @package SPT\Services\Import - */ -class KeepassImportTest extends DatabaseTestCase -{ - /** - * @var Container - */ - protected static $dic; - - /** - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - self::$dic = setupContext(); - - self::$loadFixtures = true; - } - - /** - * @throws ImportException - * @throws DependencyException - * @throws NotFoundException - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws SPException - * @throws NoSuchItemException - * @throws FileException - */ - public function testDoImport() - { - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_keepass.xml'; - - $params = new ImportParams(); - $params->setDefaultUser(1); - $params->setDefaultGroup(2); - - $import = new KeepassImport(self::$dic, new XmlFileImport(FileImport::fromFilesystem($file)), $params); - $import->doImport(); - - $this->checkImportedData(); - } - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - * @throws SPException - */ - private function checkImportedData() - { - // Checkout categories - $categoryService = self::$dic->get(CategoryService::class); - - $this->assertEquals('Linux', $categoryService->getByName('Linux')->getName()); - $this->assertEquals('Windows', $categoryService->getByName('Windows')->getName()); - $this->assertEquals('Servers', $categoryService->getByName('Servers')->getName()); - $this->assertEquals('General', $categoryService->getByName('General')->getName()); - - $this->assertEquals(11, self::getRowCount('Category')); - - // Checkout clients - $client = self::$dic->get(ClientService::class)->getByName('KeePass'); - - $this->assertEquals('KeePass', $client->getName()); - - $this->assertEquals(5, self::getRowCount('Client')); - - // Checkout accounts - $accountService = self::$dic->get(AccountService::class); - - // 1st account - $filter = new AccountSearchFilter(); - $filter->setClientId($client->getId()); - - /** @var AccountSearchVData[] $data */ - $data = $accountService->getByFilter($filter)->getDataAsArray(); - - $this->assertCount(5, $data); - - $this->assertEquals(5, $data[0]->getId()); - $this->assertEquals(1, $data[0]->getUserId()); - $this->assertEquals(2, $data[0]->getUserGroupId()); - $this->assertEquals('DC1', $data[0]->getName()); - $this->assertEquals('KeePass', $data[0]->getClientName()); - $this->assertEquals('Windows', $data[0]->getCategoryName()); - $this->assertEquals('192.168.100.1', $data[0]->getUrl()); - $this->assertEquals('ADS server', $data[0]->getNotes()); - $this->assertEquals('administrator', $data[0]->getLogin()); - - $pass = $accountService->getPasswordForId($data[0]->getId()); - - $this->assertEquals('k6V4iIAeR9SBOprLMUGV', Crypt::decrypt($pass->getPass(), $pass->getKey(), '12345678900')); - - // 2nd account - - $this->assertEquals(6, $data[1]->getId()); - $this->assertEquals(1, $data[1]->getUserId()); - $this->assertEquals(2, $data[1]->getUserGroupId()); - $this->assertEquals('debian', $data[1]->getName()); - $this->assertEquals('KeePass', $data[1]->getClientName()); - $this->assertEquals('Linux', $data[1]->getCategoryName()); - $this->assertEquals('http://debian.org', $data[1]->getUrl()); - $this->assertEquals("Some notes about the server", $data[1]->getNotes()); - $this->assertEquals('root', $data[1]->getLogin()); - - $pass = $accountService->getPasswordForId($data[1]->getId()); - - $this->assertEquals('TKr321zqCZhgbzmmAX13', Crypt::decrypt($pass->getPass(), $pass->getKey(), '12345678900')); - - // 3rd account - $this->assertEquals(7, $data[2]->getId()); - $this->assertEquals(1, $data[2]->getUserId()); - $this->assertEquals(2, $data[2]->getUserGroupId()); - $this->assertEquals('proxy', $data[2]->getName()); - $this->assertEquals('KeePass', $data[2]->getClientName()); - $this->assertEquals('Linux', $data[2]->getCategoryName()); - $this->assertEquals('192.168.0.1', $data[2]->getUrl()); - $this->assertEquals('Some notes about proxy server', $data[2]->getNotes()); - $this->assertEquals('admin', $data[2]->getLogin()); - - $pass = $accountService->getPasswordForId($data[2]->getId()); - - $this->assertEquals('TKr321zqCZhgbzmmAX13', Crypt::decrypt($pass->getPass(), $pass->getKey(), '12345678900')); - - $this->assertEquals(8, $data[3]->getId()); - $this->assertEquals(1, $data[3]->getUserId()); - $this->assertEquals(2, $data[3]->getUserGroupId()); - $this->assertEquals('Sample Entry', $data[3]->getName()); - $this->assertEquals('NewDatabase', $data[3]->getCategoryName()); - - $this->assertEquals(9, $data[4]->getId()); - $this->assertEquals(1, $data[4]->getUserId()); - $this->assertEquals(2, $data[4]->getUserGroupId()); - $this->assertEquals('Sample Entry #2', $data[4]->getName()); - $this->assertEquals('NewDatabase', $data[4]->getCategoryName()); - - $this->assertEquals(9, self::getRowCount('Account')); - } -} diff --git a/tests/SPT/Services/Import/SyspassImportTest.php b/tests/SPT/Services/Import/SyspassImportTest.php deleted file mode 100644 index 06ad7b22..00000000 --- a/tests/SPT/Services/Import/SyspassImportTest.php +++ /dev/null @@ -1,235 +0,0 @@ -. - */ - -namespace SPT\Services\Import; - -use Defuse\Crypto\Exception\CryptoException; -use DI\Container; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Core\Crypt\Crypt; -use SP\Domain\Account\Services\AccountService; -use SP\Domain\Category\Services\CategoryService; -use SP\Domain\Client\Services\ClientService; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Import\Services\FileImport; -use SP\Domain\Import\Services\ImportException; -use SP\Domain\Import\Services\ImportParams; -use SP\Domain\Import\Services\SyspassImport; -use SP\Domain\Import\Services\XmlFileImport; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SP\Infrastructure\File\FileException; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class SyspassImportTest - * - * @package SPT\Services\Import - */ -class SyspassImportTest extends DatabaseTestCase -{ - /** - * @var Container - */ - protected static $dic; - - /** - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - self::$dic = setupContext(); - - self::$loadFixtures = true; - } - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - * @throws ImportException - * @throws FileException - */ - public function testDoImport() - { - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_syspass.xml'; - - $params = new ImportParams(); - $params->setDefaultUser(1); - $params->setDefaultGroup(2); - - $import = new SyspassImport(self::$dic, new XmlFileImport(FileImport::fromFilesystem($file)), $params); - $import->doImport(); - - $this->checkImportedData(); - } - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - private function checkImportedData() - { - // Checkout categories - $this->assertEquals('CSV Category 1', self::$dic->get(CategoryService::class)->getByName('CSV Category 1')->getName()); - - $this->assertEquals(5, self::getRowCount('Category')); - - // Checkout clients - $this->assertEquals('CSV Client 1', self::$dic->get(ClientService::class)->getByName('CSV Client 1')->getName()); - - $this->assertEquals(6, self::getRowCount('Client')); - - // Checkout accounts - $accountService = self::$dic->get(AccountService::class); - - // 1st account - $expectedId = 5; - $result = $accountService->getByIdEnriched($expectedId); - $data = $result->getAccountVData(); - - $this->assertEquals($expectedId, $data->getId()); - $this->assertEquals(1, $data->getUserId()); - $this->assertEquals(2, $data->getUserGroupId()); - $this->assertEquals('Google', $data->getName()); - $this->assertEquals('Google', $data->getClientName()); - $this->assertEquals('Web', $data->getCategoryName()); - $this->assertEquals('https://google.com', $data->getUrl()); - $this->assertEmpty($data->getNotes()); - $this->assertEquals('admin', $data->getLogin()); - - $accountService->withTags($result); - - $expectedTags = [7, 8, 9]; - $i = 0; - - foreach ($result->getTags() as $tag) { - $this->assertEquals($expectedTags[$i], $tag->getId()); - $i++; - } - - $pass = $accountService->getPasswordForId($data->getId()); - - $this->assertEquals('-{?^··\mjCgetPass(), $pass->getKey(), '12345678900')); - - // 2nd account - $expectedId = 6; - $result = $accountService->getByIdEnriched($expectedId); - $data = $result->getAccountVData(); - - $this->assertEquals($expectedId, $data->getId()); - $this->assertEquals(1, $data->getUserId()); - $this->assertEquals(2, $data->getUserGroupId()); - $this->assertEquals('Google', $data->getName()); - $this->assertEquals('Google', $data->getClientName()); - $this->assertEquals('Web', $data->getCategoryName()); - $this->assertEquals('https://google.com', $data->getUrl()); - $this->assertEquals('blablacar', $data->getNotes()); - $this->assertEquals('admin', $data->getLogin()); - - $accountService->withTags($result); - - $expectedTags = [8, 9, 1]; - $i = 0; - - foreach ($result->getTags() as $tag) { - $this->assertEquals($expectedTags[$i], $tag->getId()); - $i++; - } - - $pass = $accountService->getPasswordForId($data->getId()); - - $this->assertEquals('\'ynHRMJy-fRa', Crypt::decrypt($pass->getPass(), $pass->getKey(), '12345678900')); - - // 3rd account - $expectedId = 7; - $result = $accountService->getByIdEnriched($expectedId); - $data = $result->getAccountVData(); - - $this->assertEquals($expectedId, $data->getId()); - $this->assertEquals(1, $data->getUserId()); - $this->assertEquals(2, $data->getUserGroupId()); - $this->assertEquals('Test CSV 1', $data->getName()); - $this->assertEquals('CSV Client 1', $data->getClientName()); - $this->assertEquals('CSV Category 1', $data->getCategoryName()); - $this->assertEquals('http://test.me', $data->getUrl()); - $this->assertEquals('CSV Notes', $data->getNotes()); - $this->assertEquals('csv_login1', $data->getLogin()); - - $pass = $accountService->getPasswordForId($data->getId()); - - $this->assertEquals('csv_pass1', Crypt::decrypt($pass->getPass(), $pass->getKey(), '12345678900')); - - // 4th account - $expectedId = 8; - $result = $accountService->getByIdEnriched($expectedId); - $data = $result->getAccountVData(); - - $this->assertEquals($expectedId, $data->getId()); - $this->assertEquals(1, $data->getUserId()); - $this->assertEquals(2, $data->getUserGroupId()); - $this->assertEquals('Test CSV 2', $data->getName()); - $this->assertEquals('Google', $data->getClientName()); - $this->assertEquals('Linux', $data->getCategoryName()); - $this->assertEquals('http://linux.org', $data->getUrl()); - $this->assertEquals("CSV Notes 2\nbla\nbla\ncar\n", $data->getNotes()); - $this->assertEquals('csv_login2', $data->getLogin()); - - $pass = $accountService->getPasswordForId($data->getId()); - - $this->assertEquals('csv_pass2', Crypt::decrypt($pass->getPass(), $pass->getKey(), '12345678900')); - - // 5th account - $expectedId = 9; - $result = $accountService->getByIdEnriched($expectedId); - $data = $result->getAccountVData(); - - $this->assertEquals($expectedId, $data->getId()); - $this->assertEquals(1, $data->getUserId()); - $this->assertEquals(2, $data->getUserGroupId()); - $this->assertEquals('Test CSV 3', $data->getName()); - $this->assertEquals('Apple', $data->getClientName()); - $this->assertEquals('SSH', $data->getCategoryName()); - $this->assertEquals('http://apple.com', $data->getUrl()); - $this->assertEquals('CSV Notes 3', $data->getNotes()); - $this->assertEquals('csv_login2', $data->getLogin()); - - $pass = $accountService->getPasswordForId($data->getId()); - - $this->assertEquals('csv_pass3', Crypt::decrypt($pass->getPass(), $pass->getKey(), '12345678900')); - - $this->assertEquals(9, self::getRowCount('Account')); - } -} diff --git a/tests/SPT/Services/Import/XmlFileImportTest.php b/tests/SPT/Services/Import/XmlFileImportTest.php deleted file mode 100644 index 6fdc04fc..00000000 --- a/tests/SPT/Services/Import/XmlFileImportTest.php +++ /dev/null @@ -1,87 +0,0 @@ -. - */ - -namespace SPT\Services\Import; - -use PHPUnit\Framework\TestCase; -use SP\Domain\Import\Services\FileImport; -use SP\Domain\Import\Services\ImportException; -use SP\Domain\Import\Services\XmlFileImport; -use SP\Infrastructure\File\FileException; - -/** - * Class XmlFileImportTest - * - * @package SPT\Services\Import - */ -class XmlFileImportTest extends TestCase -{ - - /** - * @throws ImportException - * @throws FileException - */ - public function testDetectXMLFormat() - { - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_syspass.xml'; - - $import = new XmlFileImport(FileImport::fromFilesystem($file)); - - $this->assertEquals('syspass', $import->detectXMLFormat()); - - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_keepass.xml'; - - $import = new XmlFileImport(FileImport::fromFilesystem($file)); - - $this->assertEquals('keepass', $import->detectXMLFormat()); - } - - /** - * @throws ImportException - * @throws FileException - */ - public function testInvalidFile() - { - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data.csv'; - - $this->expectException(ImportException::class); - - new XmlFileImport(FileImport::fromFilesystem($file)); - } - - /** - * @throws ImportException - * @throws FileException - */ - public function testEmptyFile() - { - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_empty.xml'; - - $import = new XmlFileImport(FileImport::fromFilesystem($file)); - - $this->expectException(ImportException::class); - - $import->detectXMLFormat(); - } -} diff --git a/tests/SPT/Services/Import/XmlImportTest.php b/tests/SPT/Services/Import/XmlImportTest.php deleted file mode 100644 index e9b9ec63..00000000 --- a/tests/SPT/Services/Import/XmlImportTest.php +++ /dev/null @@ -1,85 +0,0 @@ -. - */ - -namespace SPT\Services\Import; - -use DI\Container; -use SP\Core\Context\ContextException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\Import\Services\FileImport; -use SP\Domain\Import\Services\ImportException; -use SP\Domain\Import\Services\ImportParams; -use SP\Domain\Import\Services\XmlFileImport; -use SP\Domain\Import\Services\XmlImport; -use SP\Infrastructure\File\FileException; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class XmlImportTest - * - * @package SPT\Services\Import - */ -class XmlImportTest extends DatabaseTestCase -{ - /** - * @var Container - */ - protected static $dic; - - /** - * @throws ContextException - */ - public static function setUpBeforeClass(): void - { - self::$dic = setupContext(); - - self::$loadFixtures = true; - } - - /** - * @throws ImportException - * @throws FileException - * @throws SPException - */ - public function testDoImport() - { - $params = new ImportParams(); - $params->setDefaultUser(1); - $params->setDefaultGroup(1); - - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_syspass.xml'; - - $import = new XmlImport(self::$dic, new XmlFileImport(FileImport::fromFilesystem($file)), $params); - - $this->assertEquals(5, $import->doImport()->getCounter()); - - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'import' . DIRECTORY_SEPARATOR . 'data_keepass.xml'; - - $import = new XmlImport(self::$dic, new XmlFileImport(FileImport::fromFilesystem($file)), $params); - - $this->assertEquals(5, $import->doImport()->getCounter()); - } -} diff --git a/tests/SPT/Services/ItemPreset/ItemPresetServiceTest.php b/tests/SPT/Services/ItemPreset/ItemPresetServiceTest.php deleted file mode 100644 index 09a3b4fd..00000000 --- a/tests/SPT/Services/ItemPreset/ItemPresetServiceTest.php +++ /dev/null @@ -1,382 +0,0 @@ -. - */ - -namespace SPT\Services\ItemPreset; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemPreset\AccountPermission; -use SP\DataModel\ItemSearchData; -use SP\Domain\Account\Models\ItemPreset; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\NoSuchPropertyException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\ItemPreset\Services\ItemPresetRequest; -use SP\Domain\ItemPreset\Services\ItemPresetService; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class ItemPresetServiceTest - * - * @package SPT\Services\ItemPreset - */ -class ItemPresetServiceTest extends DatabaseTestCase -{ - /** - * @var ItemPresetService - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(ItemPresetService::class); - } - - public static function userDataProvider(): array - { - return [ - [1, 1, 1, 3], - [1, 2, 2, 1], - [1, 1, 3, 2], - [2, 2, 2, 2], - [2, 2, 3, 2], - [2, 1, 3, 2], - [3, 1, 1, 3], - [3, 1, 2, 2], - ]; - } - - /** - * @dataProvider userDataProvider - * - * @param int $userId - * @param int $userGroupId - * @param int $userProfileId - * @param int $expected - * - * @throws ConstraintException - * @throws QueryException - */ - public function testGetForUser($userId, $userGroupId, $userProfileId, $expected) - { - $result = self::$service->getForUser('permission', $userId, $userGroupId, $userProfileId); - - $this->assertInstanceOf(ItemPreset::class, $result); - $this->assertEquals($expected, $result->getId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testGetById() - { - $data = new ItemPreset(); - $data->id = 1; - $data->userId = 1; - $data->fixed = 0; - $data->priority = 0; - $data->type = 'permission'; - - $result = self::$service->getById(1); - - $this->assertInstanceOf(ItemPreset::class, $result); - $this->assertEquals($data, $result); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $count = self::getRowCount('ItemPreset'); - - $result = self::$service->getAll(); - $this->assertCount($count, $result); - - $this->assertInstanceOf(ItemPreset::class, $result[0]); - $this->assertEquals(1, $result[0]->getId()); - $this->assertEquals('permission', $result[0]->getType()); - $this->assertEquals(1, $result[0]->getUserId()); - $this->assertNull($result[0]->getUserGroupId()); - $this->assertNull($result[0]->getUserProfileId()); - $this->assertNull($result[0]->getData()); - $this->assertEquals(0, $result[0]->getFixed()); - $this->assertEquals(0, $result[0]->getPriority()); - - $this->assertInstanceOf(ItemPreset::class, $result[1]); - $this->assertEquals(2, $result[1]->getId()); - - $this->assertInstanceOf(ItemPreset::class, $result[2]); - $this->assertEquals(3, $result[2]->getId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - * @throws NoSuchPropertyException - */ - public function testUpdate() - { - $accountPermission = new AccountPermission(); - $accountPermission->setUsersEdit([1, 2]); - $accountPermission->setUsersView([3]); - $accountPermission->setUserGroupsView([2]); - $accountPermission->setUserGroupsEdit([1, 3]); - - $data = new ItemPreset(); - $data->id = 1; - $data->userGroupId = 1; - $data->fixed = 1; - $data->priority = 1; - $data->type = 'permission'; - - $request = new ItemPresetRequest($data, $accountPermission); - - self::$service->update($request); - - $resultData = self::$service->getById(1); - - $this->assertEquals($data, $resultData); - $this->assertEquals($accountPermission, $resultData->hydrate(AccountPermission::class)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdateUnKnown() - { - $accountPermission = new AccountPermission(); - $accountPermission->setUsersEdit([1, 2]); - $accountPermission->setUsersView([3]); - $accountPermission->setUserGroupsView([2]); - $accountPermission->setUserGroupsEdit([1, 3]); - - $data = new ItemPreset(); - $data->id = 10; - $data->userGroupId = 1; - $data->fixed = 1; - $data->priority = 1; - $data->type = 'permission'; - - $request = new ItemPresetRequest($data, $accountPermission); - - $this->assertEquals(0, self::$service->update($request)); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testDelete() - { - self::$service - ->delete(3) - ->delete(4); - - $this->assertEquals(3, self::getRowCount('ItemPreset')); - } - - /** - * @throws NoSuchItemException - * @throws ConstraintException - * @throws QueryException - */ - public function testDeleteUnKnown() - { - $this->expectException(NoSuchItemException::class); - - $this->assertEquals(0, self::$service->delete(10)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - // Search for user's name - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('demo'); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(4, $data[0]->id); - $this->assertEquals('permission', $data[0]->type); - $this->assertEquals(2, $data[0]->userId); - $this->assertNull($data[0]->userGroupId); - $this->assertNull($data[0]->userProfileId); - $this->assertNull($data[0]->data); - $this->assertEquals(0, $data[0]->fixed); - $this->assertEquals(0, $data[0]->priority); - $this->assertEquals('sysPass demo', $data[0]->userName); - - // Search for group's name - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('admins'); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(2, $data[0]->id); - $this->assertEquals('permission', $data[0]->type); - $this->assertNull($data[0]->userId); - $this->assertEquals(1, $data[0]->userGroupId); - $this->assertNull($data[0]->userProfileId); - $this->assertNull($data[0]->data); - $this->assertEquals(0, $data[0]->fixed); - $this->assertEquals(10, $data[0]->priority); - $this->assertEquals('Admins', $data[0]->userGroupName); - - // Search for profile's name - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Usuarios'); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(5, $data[0]->id); - $this->assertEquals('permission', $data[0]->type); - $this->assertNull($data[0]->userId); - $this->assertNull($data[0]->userGroupId); - $this->assertEquals(3, $data[0]->userProfileId); - $this->assertNull($data[0]->data); - $this->assertEquals(0, $data[0]->fixed); - $this->assertEquals(10, $data[0]->priority); - $this->assertEquals('Usuarios', $data[0]->userProfileName); - - // Search for no results - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('test_permission'); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetForCurrentUser() - { - $data = self::$service->getForCurrentUser('permission'); - - $this->assertInstanceOf(ItemPreset::class, $data); - $this->assertEquals(2, $data->getId()); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - * @throws NoSuchPropertyException - */ - public function testCreate() - { - $accountPermission = new AccountPermission(); - $accountPermission->setUsersEdit([1, 2]); - $accountPermission->setUsersView([3]); - $accountPermission->setUserGroupsView([2]); - $accountPermission->setUserGroupsEdit([1, 3]); - - $data = new ItemPreset(); - $data->id = 6; - $data->userGroupId = 1; - $data->fixed = 1; - $data->priority = 20; - $data->type = 'permission'; - - $request = new ItemPresetRequest($data, $accountPermission); - - $id = self::$service->create($request); - - $result = self::$service->getById($id); - - $this->assertEquals($data->id, $id); - $this->assertEquals($data, $result); - $this->assertEquals($accountPermission, $result->hydrate(AccountPermission::class)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCreateDuplicatedHash() - { - $accountPermission = new AccountPermission(); - $accountPermission->setUsersEdit([1, 2]); - $accountPermission->setUsersView([3]); - $accountPermission->setUserGroupsView([2]); - $accountPermission->setUserGroupsEdit([1, 3]); - - $data = new ItemPreset(); - $data->userGroupId = 1; - $data->fixed = 1; - $data->priority = 10; - $data->type = 'permission'; - - $request = new ItemPresetRequest($data, $accountPermission); - - $this->expectException(ConstraintException::class); - - self::$service->create($request); - } -} diff --git a/tests/SPT/Services/Notification/NotificationServiceTest.php b/tests/SPT/Services/Notification/NotificationServiceTest.php deleted file mode 100644 index dadb40d1..00000000 --- a/tests/SPT/Services/Notification/NotificationServiceTest.php +++ /dev/null @@ -1,573 +0,0 @@ -. - */ - -namespace SPT\Services\Notification; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Core\Messages\NotificationMessage; -use SP\DataModel\ItemSearchData; -use SP\DataModel\NotificationData; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Context\ContextInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Notification\Ports\NotificationServiceInterface; -use SP\Domain\Notification\Services\NotificationService; -use SP\Domain\User\Services\UserLoginResponse; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class NotificationServiceTest - * - * @package SPT\Services\Notification - */ -class NotificationServiceTest extends DatabaseTestCase -{ - /** - * @var ContextInterface - */ - private static $context; - /** - * @var NotificationServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - self::$context = $dic->get(ContextInterface::class); - - // Inicializar el servicio - self::$service = $dic->get(NotificationService::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $data = self::$service->getAll(); - - $this->assertCount(3, $data); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals(2, $data[1]->getId()); - $this->assertEquals(3, $data[2]->getId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearchForUserId() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Test'); - - $result = self::$service->searchForUserId($itemSearchData, 2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertEquals(2, $data[0]->getId()); - - $itemSearchData->setSeachString('Accounts'); - - $result = self::$service->searchForUserId($itemSearchData, 2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals(1, $data[1]->getId()); - - $itemSearchData->setSeachString('Admins'); - - $result = self::$service->searchForUserId($itemSearchData, 2); - - $this->assertEquals(0, $result->getNumRows()); - - $itemSearchData->setSeachString('Global'); - - $result = self::$service->searchForUserId($itemSearchData, 2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertEquals(2, $data[0]->getId()); - - $itemSearchData->setSeachString(''); - - $result = self::$service->searchForUserId($itemSearchData, 2); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals(1, $data[1]->getId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testGetAllActiveForNonAdmin() - { - $userData = new UserLoginResponse(); - $userData->setId(2); - $userData->setIsAdminApp(false); - - self::$context->setUserData($userData); - - $data = self::$service->getAllActiveForUserId(2); - - $this->assertCount(2, $data); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals(1, $data[1]->getId()); - - $data = self::$service->getAllActiveForUserId(3); - - $this->assertCount(1, $data); - $this->assertEquals(2, $data[0]->getId()); - - self::$service->setCheckedById(1); - - $data = self::$service->getAllActiveForUserId(2); - - $this->assertCount(1, $data); - $this->assertEquals(2, $data[0]->getId()); - - self::$service->setCheckedById(2); - - $this->assertCount(0, self::$service->getAllActiveForUserId(2)); - $this->assertCount(0, self::$service->getAllActiveForUserId(3)); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testGetAllActiveForAdmin() - { - $userData = new UserLoginResponse(); - $userData->setId(1); - $userData->setIsAdminApp(true); - - self::$context->setUserData($userData); - - $data = self::$service->getAllActiveForUserId(1); - - $this->assertCount(2, $data); - $this->assertEquals(3, $data[0]->getId()); - $this->assertEquals(2, $data[1]->getId()); - - $data = self::$service->getAllActiveForUserId(3); - - $this->assertCount(2, $data); - $this->assertEquals(3, $data[0]->getId()); - $this->assertEquals(2, $data[1]->getId()); - - self::$service->setCheckedById(2); - - $data = self::$service->getAllActiveForUserId(1); - - $this->assertCount(1, $data); - $this->assertEquals(3, $data[0]->getId()); - - self::$service->setCheckedById(3); - - $this->assertCount(0, self::$service->getAllActiveForUserId(1)); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testSetCheckedById() - { - self::$service->setCheckedById(1); - - $this->assertTrue(true); - - $this->expectException(NoSuchItemException::class); - - $this->assertEquals(0, self::$service->setCheckedById(4)); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testGetForUserIdByDate() - { - // Forces an update of the notification's date field - $this->assertEquals(1, self::$service->update(self::$service->getById(1))); - - $data = self::$service->getForUserIdByDate('Accounts', 2); - - $this->assertCount(1, $data); - $this->assertEquals(1, $data[0]->getId()); - - $this->assertCount(0, self::$service->getForUserIdByDate('Accounts', 3)); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testCreate() - { - $data = new NotificationData(); - $data->setId(4); - $data->setUserId(2); - $data->setType('Test'); - $data->setComponent('Config'); - $data->setDescription(NotificationMessage::factory()->setTitle('Prueba')->setDescription(['blablabla'])); - $data->setChecked(0); - $data->setOnlyAdmin(1); - $data->setSticky(1); - - $this->assertEquals(4, self::$service->create($data)); - - $resultData = self::$service->getById(4); - - $this->assertEquals($data->getId(), $resultData->getId()); - $this->assertEquals($data->getUserId(), $resultData->getUserId()); - $this->assertEquals($data->getType(), $resultData->getType()); - $this->assertEquals($data->getComponent(), $resultData->getComponent()); - $this->assertEquals($data->isChecked(), $resultData->isChecked()); - $this->assertEquals($data->isOnlyAdmin(), $resultData->isOnlyAdmin()); - $this->assertEquals($data->isSticky(), $resultData->isSticky()); - $this->assertGreaterThan(0, $resultData->getDate()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch() - { - $this->assertCount(0, self::$service->getByIdBatch([])); - - $data = self::$service->getByIdBatch([1, 2, 3, 4]); - - $this->assertCount(3, $data); - $this->assertInstanceOf(NotificationData::class, $data[0]); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals('Prueba', $data[0]->getType()); - $this->assertEquals('Accounts', $data[0]->getComponent()); - $this->assertEquals('Notificación de prueba', trim($data[0]->getDescription())); - $this->assertEquals(1529145158, $data[0]->getDate()); - $this->assertEquals(0, $data[0]->isChecked()); - $this->assertEquals(0, $data[0]->isOnlyAdmin()); - $this->assertEquals(0, $data[0]->isSticky()); - $this->assertEquals(2, $data[0]->getUserId()); - - $this->assertEquals(2, $data[1]->getId()); - $this->assertEquals(3, $data[2]->getId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearchNonAdmin() - { - $userData = new UserLoginResponse(); - $userData->setId(2); - $userData->setIsAdminApp(false); - - self::$context->setUserData($userData); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Test'); - - $result = self::$service->search($itemSearchData); - - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - - $this->assertCount(1, $data); - $this->assertInstanceOf(NotificationData::class, $data[0]); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals('test', $data[0]->getDescription()); - - $itemSearchData->setSeachString('Global'); - - $result = self::$service->search($itemSearchData); - - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(NotificationData::class, $data[0]); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals('Global', $data[0]->getType()); - - $itemSearchData->setSeachString(''); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $result->getDataAsArray()); - - $itemSearchData->setSeachString('Accounts'); - - $result = self::$service->search($itemSearchData); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals('Accounts', $data[0]->getComponent()); - $this->assertEquals(1, $data[1]->getId()); - $this->assertEquals('Accounts', $data[1]->getComponent()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearchAdmin() - { - $userData = new UserLoginResponse(); - $userData->setId(1); - $userData->setIsAdminApp(true); - - self::$context->setUserData($userData); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Test'); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(2, $result->getNumRows()); - - $itemSearchData->setSeachString('Global'); - - $result = self::$service->search($itemSearchData); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(NotificationData::class, $data[0]); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals('Global', $data[0]->getType()); - - $itemSearchData->setSeachString(''); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $result->getDataAsArray()); - - $itemSearchData->setSeachString('Accounts'); - - $result = self::$service->search($itemSearchData); - /** @var NotificationData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(2, $result->getNumRows()); - $this->assertCount(2, $data); - $this->assertEquals(3, $data[0]->getId()); - $this->assertEquals('Accounts', $data[0]->getComponent()); - $this->assertEquals(2, $data[1]->getId()); - $this->assertEquals('Accounts', $data[1]->getComponent()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testGetById() - { - $data = self::$service->getById(3); - - $this->assertInstanceOf(NotificationData::class, $data); - $this->assertEquals(3, $data->getId()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getById(4); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testDeleteAdminBatch() - { - $this->assertEquals(3, self::$service->deleteAdminBatch([1, 2, 3])); - - $this->assertEquals(0, self::$service->deleteAdminBatch([])); - - $this->assertEquals(0, self::getRowCount('Notification')); - - $this->expectException(ServiceException::class); - - $this->assertEquals(2, self::$service->deleteAdminBatch([4])); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testDeleteAdmin() - { - $countBefore = self::getRowCount('Notification'); - - self::$service->deleteAdmin(3); - - $this->assertEquals($countBefore - 1, self::getRowCount('Notification')); - - $this->expectException(NoSuchItemException::class); - - $this->assertEquals(1, self::$service->deleteAdmin(4)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllForUserId() - { - $data = self::$service->getAllForUserId(2); - - $this->assertCount(2, $data); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals(1, $data[1]->getId()); - - $this->assertCount(1, self::$service->getAllForUserId(3)); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testUpdate() - { - $data = new NotificationData(); - $data->setId(3); - $data->setUserId(2); - $data->setType('Test'); - $data->setComponent('Config'); - $data->setDescription(NotificationMessage::factory()->setTitle('Prueba')->setDescription(['blablabla'])); - $data->setChecked(0); - $data->setOnlyAdmin(1); - $data->setSticky(1); - - $this->assertEquals(1, self::$service->update($data)); - - $resultData = self::$service->getById(3); - - $this->assertEquals($data->getId(), $resultData->getId()); - $this->assertEquals($data->getUserId(), $resultData->getUserId()); - $this->assertEquals($data->getType(), $resultData->getType()); - $this->assertEquals($data->getComponent(), $resultData->getComponent()); - $this->assertEquals($data->isChecked(), $resultData->isChecked()); - $this->assertEquals($data->isOnlyAdmin(), $resultData->isOnlyAdmin()); - $this->assertEquals($data->isSticky(), $resultData->isSticky()); - $this->assertGreaterThan(0, $resultData->getDate()); - - $data->setId(4); - - $this->assertEquals(0, self::$service->update($data)); - - // FIXME: No exception on Travis CI?? -// $data = new NotificationData(); -// $data->setId(1); -// -// $this->expectException(ConstraintException::class); -// -// self::$service->update($data); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testDelete() - { - self::$service->delete(3); - - $this->assertEquals(2, self::getRowCount('Notification')); - - $this->expectException(NoSuchItemException::class); - - $this->assertEquals(0, self::$service->delete(4)); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(2, self::$service->deleteByIdBatch([1, 3])); - - $this->assertEquals(0, self::$service->deleteByIdBatch([])); - - $this->assertEquals(1, self::getRowCount('Notification')); - - $this->expectException(ServiceException::class); - - $this->assertEquals(2, self::$service->deleteByIdBatch([2])); - } -} diff --git a/tests/SPT/Services/Plugin/PluginDataServiceTest.php b/tests/SPT/Services/Plugin/PluginDataServiceTest.php deleted file mode 100644 index f5bcda9f..00000000 --- a/tests/SPT/Services/Plugin/PluginDataServiceTest.php +++ /dev/null @@ -1,300 +0,0 @@ -. - */ - -namespace SPT\Services\Plugin; - -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\NoSuchPropertyException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\Plugin\Ports\PluginDataInterface; -use SP\Domain\Plugin\Services\PluginData; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SP\Infrastructure\Plugin\Repositories\PluginDataModel; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class PluginDataServiceTest - * - * @package SPT\Services\Plugin - */ -class PluginDataServiceTest extends DatabaseTestCase -{ - /** - * @var PluginDataInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(PluginData::class); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws CryptoException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testUpdate() - { - $data = new PluginDataModel(); - $data->setItemId(1); - $data->setName('Authenticator'); - $data->setData('data_updated'); - - $this->assertEquals(1, self::$service->update($data)); - - $itemData = self::$service->getByItemId($data->getName(), $data->getItemId()); - - $this->assertEquals('data_updated', $itemData->getData()); - - $data = new PluginDataModel(); - $data->setItemId(0); - $data->setName('Authenticator'); - $data->setData('data_updated'); - - $this->assertEquals(0, self::$service->update($data)); - } - - /** - * @throws ConstraintException - * @throws CryptoException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testUpdateUnkown() - { - $data = new PluginDataModel(); - $data->setItemId(2); - $data->setName('Test'); - $data->setData('data'); - - $this->assertEquals(0, self::$service->update($data)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $data = self::$service->getAll(); - - $this->assertCount(4, $data); - $this->assertEquals(1, $data[0]->getItemId()); - $this->assertEquals('Authenticator', $data[0]->getName()); - $this->assertEquals('data_item1', $data[0]->getData()); - - $this->assertEquals(2, $data[1]->getItemId()); - $this->assertEquals(3, $data[2]->getItemId()); - $this->assertEquals(2, $data[3]->getItemId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDelete() - { - self::$service->delete('Authenticator'); - - $this->assertEquals(2, self::getRowCount('PluginData')); - - self::$service->delete('DokuWiki'); - - $this->assertEquals(1, self::getRowCount('PluginData')); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDeleteUnkown() - { - $this->expectException(NoSuchItemException::class); - - self::$service->delete('Test'); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws CryptoException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testCreate() - { - $data = new PluginDataModel(); - $data->setItemId(4); - $data->setName('Authenticator'); - $data->setData('data'); - - self::$service->create($data); - - $itemData = self::$service->getByItemId($data->getName(), $data->getItemId()); - - $this->assertEquals($data->getName(), $itemData->getName()); - $this->assertEquals('data', $itemData->getData()); - - $this->expectException(ConstraintException::class); - - self::$service->create($data); - } - - /** - * @throws ConstraintException - * @throws CryptoException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testCreateUnknown() - { - $this->expectException(ConstraintException::class); - - $data = new PluginDataModel(); - $data->setItemId(4); - $data->setName('Test'); - $data->setData('data'); - - self::$service->create($data); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws CryptoException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testGetByItemId() - { - $data = self::$service->getByItemId('Authenticator', 1); - - $this->assertInstanceOf(PluginDataModel::class, $data); - $this->assertEquals(1, $data->getItemId()); - $this->assertEquals('Authenticator', $data->getName()); - $this->assertEquals('data_item1', $data->getData()); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws CryptoException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testGetByItemIdUnkown() - { - $this->expectException(NoSuchItemException::class); - - self::$service->getByItemId('Test', 1); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetById() - { - $result = self::$service->getById('Authenticator'); - - $this->assertCount(2, $result); - $this->assertInstanceOf(PluginDataModel::class, $result[0]); - $this->assertEquals(1, $result[0]->getItemId()); - $this->assertEquals('Authenticator', $result[0]->getName()); - $this->assertEquals('data_item1', $result[0]->getData()); - - $this->assertInstanceOf(PluginDataModel::class, $result[1]); - $this->assertEquals(2, $result[1]->getItemId()); - $this->assertEquals('Authenticator', $result[1]->getName()); - $this->assertEquals('plugin_data', $result[1]->getData()); - - $this->assertCount(1, self::$service->getById('XML Exporter')); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetByIdUnkown() - { - $this->expectException(NoSuchItemException::class); - - self::$service->getById('Test'); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testDeleteByItemId() - { - self::$service->deleteByItemId('Authenticator', 1); - - $this->assertCount(1, self::$service->getById('Authenticator')); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testDeleteByItemIdUnkown() - { - $this->expectException(NoSuchItemException::class); - - self::$service->deleteByItemId('Test', 1); - } -} diff --git a/tests/SPT/Services/Plugin/PluginOperationTest.php b/tests/SPT/Services/Plugin/PluginOperationTest.php deleted file mode 100644 index 1cb5f972..00000000 --- a/tests/SPT/Services/Plugin/PluginOperationTest.php +++ /dev/null @@ -1,254 +0,0 @@ -. - */ - -namespace SPT\Services\Plugin; - -use Closure; -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\NoSuchPropertyException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Plugin\Ports\PluginOperationInterface; -use SP\Domain\Plugin\Services\PluginData; -use SP\Domain\Plugin\Services\PluginOperation; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class PluginOperationTest - * - * @package SPT\Services\Plugin - */ -class PluginOperationTest extends DatabaseTestCase -{ - - /** - * @var Closure - */ - private static $pluginOperation; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$pluginOperation = function ($name) use ($dic) { - return new PluginOperation($dic->get(PluginData::class), $name); - }; - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testUpdate() - { - /** @var PluginOperationInterface $pluginOperation */ - $pluginOperation = self::$pluginOperation->call($this, 'Authenticator'); - - $data = [1, 2, 3]; - - $this->assertEquals(1, $pluginOperation->update(1, $data)); - $this->assertEquals($data, $pluginOperation->get(1)); - - $data = new stdClass(); - $data->id = 1; - $data->name = 'test'; - $data->test = new stdClass(); - - $this->assertEquals(1, $pluginOperation->update(1, $data)); - $this->assertEquals($data, $pluginOperation->get(1)); - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testUpdateUnknown() - { - /** @var PluginOperationInterface $pluginOperation */ - $pluginOperation = self::$pluginOperation->call($this, 'Authenticator'); - - $data = [1, 2, 3]; - - $this->assertEquals(0, $pluginOperation->update(4, $data)); - $this->assertNull($pluginOperation->get(4)); - - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testUpdateWrongPlugin() - { - /** @var PluginOperationInterface $pluginOperation */ - $pluginOperation = self::$pluginOperation->call($this, 'Test'); - - $data = [1, 2, 3]; - - $this->assertEquals(0, $pluginOperation->update(1, $data)); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testDelete() - { - $this->assertEquals(4, self::getRowCount('PluginData')); - - /** @var PluginOperationInterface $pluginOperation */ - $pluginOperation = self::$pluginOperation->call($this, 'Authenticator'); - $pluginOperation->delete(1); - - $this->assertEquals(3, self::getRowCount('PluginData')); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testDeleteUnknown() - { - /** @var PluginOperationInterface $pluginOperation */ - $pluginOperation = self::$pluginOperation->call($this, 'Authenticator'); - - $this->expectException(NoSuchItemException::class); - - $pluginOperation->delete(4); - } - - - public function testGet() - { - $this->markTestSkipped('Already tested'); - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testGetUnknown() - { - /** @var PluginOperationInterface $pluginOperation */ - $pluginOperation = self::$pluginOperation->call($this, 'Authenticator'); - - $this->assertNull($pluginOperation->get(4)); - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testCreate() - { - /** @var PluginOperationInterface $pluginOperation */ - $pluginOperation = self::$pluginOperation->call($this, 'Authenticator'); - - $data = new stdClass(); - $data->id = 1; - $data->name = 'test'; - $data->test = new stdClass(); - - $pluginOperation->create(4, $data); - - $this->assertEquals($data, $pluginOperation->get(4)); - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testCreateDuplicated() - { - /** @var PluginOperationInterface $pluginOperation */ - $pluginOperation = self::$pluginOperation->call($this, 'Authenticator'); - - $data = new stdClass(); - $data->id = 1; - $data->name = 'test'; - $data->test = new stdClass(); - - $this->expectException(ConstraintException::class); - - $this->assertEquals(1, $pluginOperation->create(2, $data)); - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws NoSuchPropertyException - * @throws QueryException - * @throws ServiceException - */ - public function testCreateWrongPlugin() - { - /** @var PluginOperationInterface $pluginOperation */ - $pluginOperation = self::$pluginOperation->call($this, 'Test'); - - $data = new stdClass(); - $data->id = 1; - $data->name = 'test'; - $data->test = new stdClass(); - - $this->expectException(ConstraintException::class); - - $this->assertEquals(1, $pluginOperation->create(2, $data)); - } -} diff --git a/tests/SPT/Services/Plugin/PluginServiceTest.php b/tests/SPT/Services/Plugin/PluginServiceTest.php deleted file mode 100644 index fe4f864c..00000000 --- a/tests/SPT/Services/Plugin/PluginServiceTest.php +++ /dev/null @@ -1,387 +0,0 @@ -. - */ - -namespace SPT\Services\Plugin; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemData; -use SP\DataModel\ItemSearchData; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\Plugin\Ports\PluginManagerInterface; -use SP\Domain\Plugin\Services\PluginManager; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SP\Infrastructure\Plugin\Repositories\PluginModel; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class PluginServiceTest - * - * @package SPT\Services\Plugin - */ -class PluginServiceTest extends DatabaseTestCase -{ - /** - * @var PluginManagerInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(PluginManager::class); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testUpdate() - { - $data = new PluginModel(); - $data->setId(1); - $data->setName('Authenticator 2'); - $data->setAvailable(1); - $data->setEnabled(1); - $data->setData('data'); - - $this->assertEquals(1, self::$service->update($data)); - - $result = self::$service->getById(1); - - $this->assertEquals($data, $result); - - $data->setId(null); - $data->setName('Authenticator'); - - $this->assertEquals(0, self::$service->update($data)); - - $data->setId(2); - $data->setName('DokuWiki'); - - $this->expectException(ConstraintException::class); - - self::$service->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDeleteByIdBatch() - { - self::$service->deleteByIdBatch([1, 2]); - - $this->assertEquals(1, self::getRowCount('Plugin')); - - $this->expectException(ServiceException::class); - - self::$service->deleteByIdBatch([4]); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testToggleAvailable() - { - self::$service->toggleAvailable(1, false); - - $data = self::$service->getById(1); - - $this->assertEquals(0, $data->getAvailable()); - - $this->expectException(NoSuchItemException::class); - - self::$service->toggleAvailable(4, true); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testResetById() - { - $this->assertEquals(1, self::$service->resetById(2)); - - $data = self::$service->getById(2); - - $this->assertNull($data->getData()); - - $this->expectException(NoSuchItemException::class); - - self::$service->resetById(4); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetByName() - { - $data = self::$service->getByName('Authenticator'); - - $this->assertInstanceOf(PluginModel::class, $data); - $this->assertEquals(1, $data->getId()); - $this->assertEquals('Authenticator', $data->getName()); - $this->assertNull($data->getData()); - $this->assertEquals(1, $data->getAvailable()); - $this->assertEquals(0, $data->getEnabled()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getByName('Authenticator 2'); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDelete() - { - self::$service->delete(1); - - $this->assertEquals(2, self::getRowCount('Plugin')); - - $this->expectException(NoSuchItemException::class); - - self::$service->getById(1); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Auth'); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(1, $result->getNumRows()); - - /** @var PluginModel[] $data */ - $data = $result->getDataAsArray(); - - $this->assertCount(1, $data); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals('Authenticator', $data[0]->getName()); - $this->assertEquals(0, $data[0]->getEnabled()); - $this->assertEquals(1, $data[0]->getAvailable()); - - $itemSearchData->setSeachString('test'); - - $result = self::$service->search($itemSearchData); - $this->assertEquals(0, $result->getNumRows()); - - $itemSearchData->setSeachString(''); - - $result = self::$service->search($itemSearchData); - $this->assertEquals(3, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetById() - { - $data = self::$service->getById(1); - - $this->assertInstanceOf(PluginModel::class, $data); - $this->assertEquals(1, $data->getId()); - $this->assertEquals('Authenticator', $data->getName()); - $this->assertNull($data->getData()); - $this->assertEquals(1, $data->getAvailable()); - $this->assertEquals(0, $data->getEnabled()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getById(4); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testCreate() - { - $data = new PluginModel(); - $data->setId(4); - $data->setName('Authenticator 2'); - $data->setAvailable(1); - $data->setEnabled(1); - $data->setData('data'); - - $this->assertEquals(4, self::$service->create($data)); - - $this->assertEquals($data, self::$service->getById(4)); - - $this->expectException(ConstraintException::class); - - self::$service->create($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCreateBlank() - { - $this->expectException(ConstraintException::class); - - self::$service->create(new PluginModel()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetEnabled() - { - $data = self::$service->getEnabled(); - - $this->assertCount(2, $data); - $this->assertInstanceOf(ItemData::class, $data[0]); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals('XML Exporter', $data[0]->getName()); - $this->assertInstanceOf(ItemData::class, $data[1]); - $this->assertEquals(3, $data[1]->getId()); - $this->assertEquals('DokuWiki', $data[1]->getName()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAll() - { - $data = self::$service->getAll(); - - $this->assertCount(3, $data); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals('Authenticator', $data[0]->getName()); - $this->assertNull($data[0]->getData()); - $this->assertEquals(1, $data[0]->getAvailable()); - $this->assertEquals(0, $data[0]->getEnabled()); - - $this->assertEquals(3, $data[1]->getId()); - $this->assertEquals(2, $data[2]->getId()); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testToggleEnabledByName() - { - self::$service->toggleEnabledByName('Authenticator', true); - - $data = self::$service->getByName('Authenticator'); - - $this->assertEquals(1, $data->getEnabled()); - - $this->expectException(NoSuchItemException::class); - - self::$service->toggleEnabledByName('Test', false); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testToggleAvailableByName() - { - self::$service->toggleAvailableByName('Authenticator', false); - - $data = self::$service->getByName('Authenticator'); - - $this->assertEquals(0, $data->getAvailable()); - - $this->expectException(NoSuchItemException::class); - - self::$service->toggleAvailableByName('Authenticator 2', true); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetByIdBatch() - { - $data = self::$service->getByIdBatch([1, 2, 3]); - - $this->assertCount(3, $data); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals(2, $data[1]->getId()); - $this->assertEquals(3, $data[2]->getId()); - - $this->assertCount(0, self::$service->getByIdBatch([4])); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testToggleEnabled() - { - self::$service->toggleEnabled(1, true); - - $data = self::$service->getById(1); - - $this->assertEquals(1, $data->getEnabled()); - - $this->expectException(NoSuchItemException::class); - - self::$service->toggleEnabled(4, false); - } -} diff --git a/tests/SPT/Services/PublicLink/PublicLinkServiceTest.php b/tests/SPT/Services/PublicLink/PublicLinkServiceTest.php deleted file mode 100644 index 7145873e..00000000 --- a/tests/SPT/Services/PublicLink/PublicLinkServiceTest.php +++ /dev/null @@ -1,466 +0,0 @@ -. - */ - -namespace SPT\Services\PublicLink; - -use Defuse\Crypto\Exception\CryptoException; -use Defuse\Crypto\Exception\EnvironmentIsBrokenException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Core\Crypt\Vault; -use SP\DataModel\AccountExtData; -use SP\DataModel\ItemSearchData; -use SP\DataModel\PublicLinkData; -use SP\DataModel\PublicLinkListData; -use SP\Domain\Account\Ports\PublicLinkServiceInterface; -use SP\Domain\Account\Services\PublicLinkService; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Config\Ports\ConfigDataInterface; -use SP\Domain\Core\Crypt\VaultInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SP\Util\PasswordUtil; -use SP\Util\Util; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class PublicLinkServiceTest - * - * @package SPT\Services\PublicLink - */ -class PublicLinkServiceTest extends DatabaseTestCase -{ - /** - * @var string - */ - private static $salt; - /** - * @var PublicLinkServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(PublicLinkService::class); - - self::$salt = $dic->get(ConfigDataInterface::class)->getPasswordSalt(); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllBasic() - { - $data = self::$service->getAllBasic(); - - $this->assertInstanceOf(PublicLinkListData::class, $data[0]); - $this->assertEquals(2, $data[0]->getId()); - - $this->assertInstanceOf(PublicLinkListData::class, $data[1]); - $this->assertEquals(3, $data[1]->getId()); - $this->assertEquals(2, $data[1]->getItemId()); - $this->assertEquals('ac744b6948823cb0514546c567981ce4fe7240df396826d99f24fd9a1344', $data[1]->getHash()); - $this->assertNotEmpty($data[1]->getData()); - $this->assertEquals(1, $data[1]->getUserId()); - $this->assertEquals(1, $data[1]->getTypeId()); - $this->assertEquals(0, $data[1]->isNotify()); - $this->assertEquals(1529276100, $data[1]->getDateAdd()); - $this->assertEquals(1532280828, $data[1]->getDateExpire()); - $this->assertEquals(0, $data[1]->getDateUpdate()); - $this->assertEquals(0, $data[1]->getCountViews()); - $this->assertEquals(3, $data[1]->getMaxCountViews()); - $this->assertEquals(0, $data[1]->getTotalCountViews()); - $this->assertNull($data[1]->getUseInfo()); - $this->assertEquals('Apple', $data[1]->getAccountName()); - $this->assertEquals('admin', $data[1]->getUserLogin()); - } - - /** - * @throws SPException - */ - public function testGetByHash() - { - $hash = 'ced3400ea170619ad7d2589488b6b60747ea99f12e220f5a910ede6d834f'; - - $data = self::$service->getByHash($hash); - - $this->assertInstanceOf(PublicLinkData::class, $data); - $this->assertEquals(2, $data->getId()); - $this->assertEquals(1, $data->getItemId()); - $this->assertEquals($hash, $data->getHash()); - $this->assertNotEmpty($data->getData()); - $this->assertEquals(1, $data->getUserId()); - $this->assertEquals(1, $data->getTypeId()); - $this->assertEquals(0, $data->isNotify()); - $this->assertEquals(1529228863, $data->getDateAdd()); - $this->assertEquals(1532280825, $data->getDateExpire()); - $this->assertEquals(0, $data->getDateUpdate()); - $this->assertEquals(0, $data->getCountViews()); - $this->assertEquals(3, $data->getMaxCountViews()); - $this->assertEquals(0, $data->getTotalCountViews()); - $this->assertNull($data->getUseInfo()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getByHash(''); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Google'); - - $result = self::$service->search($itemSearchData); - /** @var PublicLinkListData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(PublicLinkListData::class, $data[0]); - $this->assertEquals(2, $data[0]->getId()); - $this->assertEquals(1, $data[0]->getItemId()); - $this->assertEquals('ced3400ea170619ad7d2589488b6b60747ea99f12e220f5a910ede6d834f', $data[0]->getHash()); - $this->assertNotEmpty($data[0]->getData()); - $this->assertEquals(1, $data[0]->getUserId()); - $this->assertEquals(1, $data[0]->getTypeId()); - $this->assertEquals(0, $data[0]->isNotify()); - $this->assertEquals(1529228863, $data[0]->getDateAdd()); - $this->assertEquals(1532280825, $data[0]->getDateExpire()); - $this->assertEquals(0, $data[0]->getDateUpdate()); - $this->assertEquals(0, $data[0]->getCountViews()); - $this->assertEquals(3, $data[0]->getMaxCountViews()); - $this->assertEquals(0, $data[0]->getTotalCountViews()); - $this->assertNull($data[0]->getUseInfo()); - $this->assertEquals('Google', $data[0]->getAccountName()); - $this->assertEquals('admin', $data[0]->getUserLogin()); - - $itemSearchData->setSeachString('Apple'); - - $result = self::$service->search($itemSearchData); - /** @var PublicLinkListData[] $data */ - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(PublicLinkListData::class, $data[0]); - $this->assertEquals(3, $data[0]->getId()); - $this->assertEquals(2, $data[0]->getItemId()); - - $itemSearchData->setSeachString(''); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(2, $result->getNumRows()); - } - - /** - * @throws NoSuchItemException - * @throws ConstraintException - * @throws QueryException - */ - public function testGetHashForItem() - { - $data = self::$service->getHashForItem(2); - - $this->assertEquals(3, $data->getId()); - $this->assertEquals('ac744b6948823cb0514546c567981ce4fe7240df396826d99f24fd9a1344', $data->getHash()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getHashForItem(3); - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testCreate() - { - self::$service->delete(2); - - $data = new PublicLinkData(); - $data->setItemId(1); - $data->setHash(PasswordUtil::generateRandomBytes()); - $data->setUserId(1); - $data->setTypeId(1); - $data->setNotify(1); - $data->setDateExpire(time() + 600); - $data->setDateAdd(time()); - $data->setMaxCountViews(3); - - $this->assertEquals(4, self::$service->create($data)); - - /** @var PublicLinkListData $resultData */ - $resultData = self::$service->getById(4); - - $this->assertEquals(4, $resultData->getId()); - $this->assertEquals($data->getItemId(), $resultData->getItemId()); - $this->assertEquals($data->getHash(), $resultData->getHash()); - $this->assertEquals($data->getUserId(), $resultData->getUserId()); - $this->assertEquals($data->getTypeId(), $resultData->getTypeId()); - $this->assertEquals($data->isNotify(), $resultData->isNotify()); - $this->assertEquals($data->getDateExpire(), $resultData->getDateExpire()); - $this->assertEquals($data->getMaxCountViews(), $resultData->getMaxCountViews()); - - $this->checkVaultData($resultData); - - $this->expectException(DuplicatedItemException::class); - - self::$service->create($data); - } - - /** - * @param PublicLinkListData $data - * - * @throws CryptoException - */ - private function checkVaultData(PublicLinkListData $data) - { - $this->assertNotEmpty($data->getData()); - - /** @var VaultInterface $vault */ - $vault = Util::unserialize(Vault::class, $data->getData()); - - $this->assertInstanceOf(Vault::class, $vault); - - /** @var AccountExtData $accountData */ - $accountData = Util::unserialize(AccountExtData::class, $vault->getData(self::$service->getPublicLinkKey($data->getHash())->getKey())); - $this->assertInstanceOf(AccountExtData::class, $accountData); - $this->assertEquals($data->getItemId(), $accountData->getId()); - } - - /** - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testCreateSameItemId() - { - $data = new PublicLinkData(); - $data->setItemId(2); - $data->setHash(PasswordUtil::generateRandomBytes()); - $data->setData('data'); - $data->setUserId(1); - $data->setTypeId(1); - $data->setNotify(1); - $data->setDateExpire(time() + 600); - $data->setDateAdd(time()); - $data->setMaxCountViews(3); - - $this->expectException(DuplicatedItemException::class); - - self::$service->create($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDelete() - { - self::$service->delete(2); - self::$service->delete(3); - - $this->assertEquals(0, self::getRowCount('PublicLink')); - - $this->expectException(NoSuchItemException::class); - - $this->assertEquals(0, self::$service->delete(10)); - } - - /** - * @throws ConstraintException - * @throws CryptoException - * @throws EnvironmentIsBrokenException - * @throws QueryException - * @throws SPException - */ - public function testRefresh() - { - $this->assertEquals(1, self::$service->refresh(2)); - - /** @var PublicLinkListData $data */ - $data = self::$service->getById(2); - - $this->checkVaultData($data); - - $this->expectException(NoSuchItemException::class); - - self::$service->refresh(4); - } - - /** - * @throws ConstraintException - * @throws ServiceException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(2, self::$service->deleteByIdBatch([2, 3])); - - $this->assertEquals(0, self::getRowCount('PublicLink')); - - $this->expectException(ServiceException::class); - - self::$service->deleteByIdBatch([10]); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testAddLinkView() - { - $hash = 'ac744b6948823cb0514546c567981ce4fe7240df396826d99f24fd9a1344'; - - $useInfo[] = [ - 'who' => SELF_IP_ADDRESS, - 'time' => time(), - 'hash' => $hash, - 'agent' => 'Mozilla/Firefox', - 'https' => true - ]; - - $data = new PublicLinkData(); - $data->setHash($hash); - $data->setUseInfo($useInfo); - - self::$service->addLinkView($data); - - /** @var PublicLinkData $resultData */ - $resultData = self::$service->getByHash($hash); - - $this->assertEquals(1, $resultData->getCountViews()); - $this->assertEquals(1, $resultData->getTotalCountViews()); - $this->assertCount(2, unserialize($resultData->getUseInfo())); - - $this->expectException(NoSuchItemException::class); - - $data->setHash('123'); - - self::$service->addLinkView($data); - } - - /** - * @throws ConstraintException - * @throws EnvironmentIsBrokenException - * @throws QueryException - * @throws SPException - */ - public function testUpdate() - { - $data = new PublicLinkData(); - $data->setId(3); - $data->setItemId(2); - $data->setHash(PasswordUtil::generateRandomBytes()); - $data->setData('data'); - $data->setUserId(2); - $data->setTypeId(1); - $data->setNotify(0); - $data->setDateExpire(time() + 3600); - $data->setDateAdd(time()); - $data->setMaxCountViews(6); - - $this->assertEquals(1, self::$service->update($data)); - - /** @var PublicLinkListData $resultData */ - $resultData = self::$service->getById(3); - - $this->assertEquals(3, $resultData->getId()); - $this->assertEquals($data->getItemId(), $resultData->getItemId()); - $this->assertEquals($data->getHash(), $resultData->getHash()); - $this->assertEquals($data->getData(), $resultData->getData()); - $this->assertEquals($data->getUserId(), $resultData->getUserId()); - $this->assertEquals($data->getTypeId(), $resultData->getTypeId()); - $this->assertEquals($data->isNotify(), $resultData->isNotify()); - $this->assertEquals($data->getDateExpire(), $resultData->getDateExpire()); - $this->assertEquals($data->getDateAdd(), $resultData->getDateAdd()); - $this->assertEquals($data->getMaxCountViews(), $resultData->getMaxCountViews()); - - $this->expectException(ConstraintException::class); - - $data->setItemId(1); - - self::$service->update($data); - } - - /** - * @throws SPException - * @throws CryptoException - */ - public function testGetById() - { - $data = self::$service->getById(2); - - $this->assertInstanceOf(PublicLinkListData::class, $data); - $this->assertEquals(2, $data->getId()); - $this->assertEquals(1, $data->getItemId()); - $this->assertEquals('ced3400ea170619ad7d2589488b6b60747ea99f12e220f5a910ede6d834f', $data->getHash()); - $this->assertEquals(1, $data->getUserId()); - $this->assertEquals(1, $data->getTypeId()); - $this->assertEquals(0, $data->isNotify()); - $this->assertEquals(1529228863, $data->getDateAdd()); - $this->assertEquals(1532280825, $data->getDateExpire()); - $this->assertEquals(0, $data->getDateUpdate()); - $this->assertEquals(0, $data->getCountViews()); - $this->assertEquals(3, $data->getMaxCountViews()); - $this->assertEquals(0, $data->getTotalCountViews()); - $this->assertNull($data->getUseInfo()); - $this->assertEquals('Google', $data->getAccountName()); - $this->assertEquals('admin', $data->getUserLogin()); - - $this->checkVaultData($data); - - $this->expectException(NoSuchItemException::class); - - self::$service->getById(10); - } -} diff --git a/tests/SPT/Services/Tag/TagServiceTest.php b/tests/SPT/Services/Tag/TagServiceTest.php deleted file mode 100644 index 7cec7857..00000000 --- a/tests/SPT/Services/Tag/TagServiceTest.php +++ /dev/null @@ -1,243 +0,0 @@ -. - */ - -namespace SPT\Services\Tag; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemSearchData; -use SP\DataModel\TagData; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\Tag\Ports\TagServiceInterface; -use SP\Domain\Tag\Services\TagService; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class TagServiceTest - * - * @package SPT\Services\Tag - */ -class TagServiceTest extends DatabaseTestCase -{ - /** - * @var TagServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(TagService::class); - } - - /** - * @throws SPException - */ - public function testDeleteByIdBatch() - { - self::$service->deleteByIdBatch([1, 2, 3]); - - $this->assertEquals(0, self::getRowCount('Tag')); - - $this->expectException(ServiceException::class); - - self::$service->deleteByIdBatch([4]); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testDelete() - { - self::$service->delete(1); - - self::$service->delete(2); - - $this->assertEquals(1, self::getRowCount('Tag')); - - $this->expectException(NoSuchItemException::class); - - self::$service->delete(10); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdate() - { - $tagData = new TagData(); - $tagData->id = 1; - $tagData->name = 'Servidor'; - - self::$service->update($tagData); - - $data = self::$service->getById(1); - - $this->assertEquals($data->getName(), $tagData->name); - - // Comprobar la a actualización con un nombre duplicado comprobando su hash - $tagData = new TagData(); - $tagData->id = 1; - $tagData->name = ' linux.'; - - $this->expectException(DuplicatedItemException::class); - - self::$service->update($tagData); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetById() - { - $data = self::$service->getById(1); - - $this->assertEquals(1, $data->getId()); - $this->assertEquals('www', $data->getName()); - - $data = self::$service->getById(2); - - $this->assertEquals(2, $data->getId()); - $this->assertEquals('windows', $data->getName()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getById(10); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllBasic() - { - $results = self::$service->getAllBasic(); - - $this->assertCount(3, $results); - - $this->assertInstanceOf(TagData::class, $results[0]); - $this->assertEquals('Linux', $results[0]->getName()); - - $this->assertInstanceOf(TagData::class, $results[1]); - $this->assertEquals('windows', $results[1]->getName()); - - $this->assertInstanceOf(TagData::class, $results[2]); - $this->assertEquals('www', $results[2]->getName()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('www'); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(1, $data[0]->id); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('prueba'); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $result->getDataAsArray()); - } - - /** - * @throws ConstraintException - * @throws DuplicatedItemException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testCreate() - { - $tagData = new TagData(); - $tagData->name = 'Core'; - - $id = self::$service->create($tagData); - - // Comprobar que el Id devuelto corresponde con la etiqueta creada - $data = self::$service->getById($id); - - $this->assertEquals($tagData->name, $data->getName()); - - $this->assertEquals(4, self::getRowCount('Tag')); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetByName() - { - $data = self::$service->getByName('www'); - - $this->assertEquals(1, $data->getId()); - $this->assertEquals('www', $data->getName()); - - $data = self::$service->getByName('windows'); - - $this->assertEquals(2, $data->getId()); - $this->assertEquals('windows', $data->getName()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getByName('test'); - } -} diff --git a/tests/SPT/Services/Task/TaskServiceTest.php b/tests/SPT/Services/Task/TaskServiceTest.php deleted file mode 100644 index 0ba02fbc..00000000 --- a/tests/SPT/Services/Task/TaskServiceTest.php +++ /dev/null @@ -1,130 +0,0 @@ -. - */ - -namespace SPT\Services\Task; - -use PHPUnit\Framework\TestCase; -use SP\Core\Context\ContextException; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Task\Services\Task; -use SP\Domain\Task\Services\TaskFactory; -use SP\Domain\Task\Services\TaskService; -use SP\Infrastructure\File\FileException; - -use function SPT\setupContext; - -/** - * Class TaskServiceTest - * - * @package SPT\Services\Task - */ -class TaskServiceTest extends TestCase -{ - private static $pids = []; - - /** - * @throws FileException - * @throws ContextException - * @throws ServiceException - */ - public function testTrackStatus() - { - $this->markTestSkipped(); - - $task = TaskFactory::register(__FUNCTION__, Task::genTaskId(__FUNCTION__)); - - $this->assertFileExists($task->getFileTask()->getFile()); - - TaskFactory::update($task, - TaskFactory::createMessage($task->getTaskId(), "Test Task (INIT)") - ); - - $dic = setupContext(); - - $this->fork(function () use ($task, $dic) { - $taskService = new TaskService($dic); - - $taskService->trackStatus($task->getTaskId(), - function ($id, $message) { - logger("id: $id; data: $message"); - }); - }); - - $this->fork(function () use ($task) { - $count = 0; - - while ($count < 2) { - sleep(10); - - TaskFactory::update($task, - TaskFactory::createMessage($task->getTaskId(), "Test Task #$count") - ); - - $count++; - } - - TaskFactory::end($task); - }); - - while (count(self::$pids) > 0) { - foreach (self::$pids as $key => $pid) { - $res = pcntl_waitpid($pid, $status); - - // If the process has already exited - if ($res == -1 || $res > 0) { - unset(self::$pids[$key]); - } - } - - sleep(1); - } - - $this->assertFileDoesNotExist($task->getFileTask()->getFile()); - $this->assertFileDoesNotExist($task->getFileOut()->getFile()); - } - - /** - * Fork for running a piece of code in child process - * - * @param callable $code - */ - private function fork(callable $code) - { - $pid = pcntl_fork(); - - if ($pid == -1) { - die('Could not fork'); - } elseif ($pid === 0) { - echo "Child execution\n"; - - $code(); - - exit(); - } else { - echo "Child $pid\n"; - - self::$pids[] = $pid; - } - } -} diff --git a/tests/SPT/Services/Track/TrackServiceTest.php b/tests/SPT/Services/Track/TrackServiceTest.php deleted file mode 100644 index 2c3bd9e6..00000000 --- a/tests/SPT/Services/Track/TrackServiceTest.php +++ /dev/null @@ -1,212 +0,0 @@ -. - */ - -namespace SPT\Services\Track; - -use DI\DependencyException; -use DI\NotFoundException; -use Exception; -use SP\Core\Context\ContextException; -use SP\DataModel\TrackData; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\InvalidArgumentException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Security\Ports\TrackServiceInterface; -use SP\Domain\Security\Services\TrackService; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SP\Infrastructure\Security\Repositories\TrackRequest; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class TrackServiceTest - * - * @package SPT\Services\Track - */ -class TrackServiceTest extends DatabaseTestCase -{ - /** - * @var TrackServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(TrackService::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testDelete() - { - self::$service->delete(1); - - $this->assertEquals(5, self::getRowCount('Track')); - - $this->expectException(NoSuchItemException::class); - - self::$service->delete(10); - } - - /** - * @throws NoSuchItemException - * @throws ConstraintException - * @throws InvalidArgumentException - * @throws QueryException - * @throws ServiceException - */ - public function testAdd() - { - $data = new TrackRequest(time(), __METHOD__, 1); - $data->setTrackIp('192.168.0.1'); - - $this->assertEquals(7, self::$service->add($data)); - - /** @var TrackData $resultData */ - $resultData = self::$service->getById(7); - - $this->assertEquals(7, $resultData->getId()); - $this->assertEquals($data->userId, $resultData->getUserId()); - $this->assertEquals($data->time, $resultData->getTime()); - $this->assertEquals($data->source, $resultData->getSource()); - $this->assertEquals('192.168.0.1', $resultData->getIpv4()); - } - - /** - * @throws ServiceException - * @throws ConstraintException - * @throws QueryException - */ - public function testAddNoAddress() - { - $data = new TrackRequest(time(), __METHOD__, 1); - - $this->expectException(ServiceException::class); - - self::$service->add($data); - } - - /** - * @throws ConstraintException - * @throws InvalidArgumentException - * @throws QueryException - */ - public function testGetAll() - { - $data = self::$service->getAll(); - - $this->assertCount(6, $data); - $this->assertInstanceOf(TrackData::class, $data[0]); - $this->assertEquals(1, $data[0]->getId()); - $this->assertEquals(0, $data[0]->getUserId()); - $this->assertEquals('1529145183', $data[0]->getTime()); - $this->assertEquals('login', $data[0]->getSource()); - $this->assertEquals('172.22.0.1', $data[0]->getIpv4()); - $this->assertEquals('', $data[0]->getIpv6()); - } - - /** - * @throws NoSuchItemException - * @throws ConstraintException - * @throws InvalidArgumentException - * @throws QueryException - */ - public function testGetById() - { - $data = self::$service->getById(1); - - $this->assertInstanceOf(TrackData::class, $data); - $this->assertEquals(1, $data->getId()); - $this->assertEquals(0, $data->getUserId()); - $this->assertEquals('1529145183', $data->getTime()); - $this->assertEquals('login', $data->getSource()); - $this->assertEquals('172.22.0.1', $data->getIpv4()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getById(10); - } - - /** - * @throws InvalidArgumentException - * @throws Exception - */ - public function testCheckTracking() - { - $this->assertFalse(self::$service->checkTracking(self::$service->getTrackRequest(__CLASS__))); - - for ($i = 1; $i <= 10; $i++) { - self::$service->add(self::$service->getTrackRequest(__CLASS__)); - } - - $this->assertTrue(self::$service->checkTracking(self::$service->getTrackRequest(__CLASS__))); - } - - /** - * @throws ConstraintException - * @throws InvalidArgumentException - * @throws QueryException - */ - public function testGetTracksForClientFromTime() - { - $data = new TrackRequest(1529272367, 'login'); - $data->setTrackIp('172.22.0.1'); - - $this->assertEquals(3, self::$service->getTracksForClientFromTime($data)); - - $data->time = time(); - - $this->assertEquals(0, self::$service->getTracksForClientFromTime($data)); - } - - public function testClear() - { - $this->markTestIncomplete(); - } - - public function testUnlock() - { - $this->markTestIncomplete(); - } - - public function testSearch() - { - $this->markTestIncomplete(); - } -} diff --git a/tests/SPT/Services/User/UserPassServiceTest.php b/tests/SPT/Services/User/UserPassServiceTest.php deleted file mode 100644 index 3d5c3ff4..00000000 --- a/tests/SPT/Services/User/UserPassServiceTest.php +++ /dev/null @@ -1,226 +0,0 @@ -. - */ - -namespace SPT\Services\User; - -use Closure; -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Core\Crypt\Crypt; -use SP\DataModel\UserLoginData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\Services\UserPassServiceInterface; -use SP\Domain\User\Services\UserLoginResponse; -use SP\Domain\User\Services\UserPassService; -use SP\Domain\User\Services\UserService; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class UserPassServiceTest - * - * @package SPT\Services\User - */ -class UserPassServiceTest extends DatabaseTestCase -{ - public const CURRENT_MASTERPASS = '12345678900'; - public const NEW_MASTERPASS = '00123456789'; - - /** - * @var Closure - */ - private static $getUserLoginResponse; - - /** - * @var UserPassServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - * @throws SPException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(UserPassService::class); - - self::$getUserLoginResponse = function ($login) use ($dic) { - return UserService::mapUserLoginResponse($dic->get(UserService::class)->getByLogin($login)); - }; - } - - /** - * @throws CryptoException - * @throws SPException - */ - public function testCreateMasterPass() - { - $result = self::$service->createMasterPass(self::NEW_MASTERPASS, 'admin', 'test123'); - - $key = self::$service->makeKeyForUser('admin', 'test123'); - - $this->assertEquals(self::NEW_MASTERPASS, Crypt::decrypt($result->getCryptMasterPass(), $result->getCryptSecuredKey(), $key)); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testMigrateUserPassById() - { - self::$service->migrateUserPassById(2, '123'); - - $this->expectException(NoSuchItemException::class); - - self::$service->migrateUserPassById(10, '123'); - } - - /** - * @throws CryptoException - * @throws SPException - */ - public function testUpdateMasterPassFromOldPass() - { - $data = new UserLoginData(); - $data->setLoginUser('admin'); - $data->setLoginPass('debian'); - $data->setUserLoginResponse(self::$getUserLoginResponse->call($this, $data->getLoginUser())); - - $result = self::$service->updateMasterPassFromOldPass('debian', $data); - - $this->assertEquals(UserPassService::MPASS_OK, $result->getStatus()); - - $result = self::$service->updateMasterPassFromOldPass('test123', $data); - - $this->assertEquals(UserPassService::MPASS_WRONG, $result->getStatus()); - } - - /** - * @throws SPException - */ - public function testLoadUserMPass() - { - $data = new UserLoginData(); - $data->setLoginUser('admin'); - $data->setLoginPass('debian'); - $data->setUserLoginResponse(self::$getUserLoginResponse->call($this, $data->getLoginUser())); - - $result = self::$service->loadUserMPass($data); - - $this->assertEquals(UserPassService::MPASS_OK, $result->getStatus()); - - $result = self::$service->loadUserMPass($data, 'test123'); - - $this->assertEquals(UserPassService::MPASS_CHECKOLD, $result->getStatus()); - } - - /** - * @throws SPException - */ - public function testLoadUserMPassOutdated() - { - $data = new UserLoginData(); - $data->setLoginUser('admin'); - $data->setLoginPass('debian'); - - /** @var UserLoginResponse $userData */ - $userData = self::$getUserLoginResponse->call($this, $data->getLoginUser()); - $userData->setLastUpdateMPass(1521887150); - - $data->setUserLoginResponse($userData); - - $result = self::$service->loadUserMPass($data); - - $this->assertEquals(UserPassService::MPASS_CHANGED, $result->getStatus()); - } - - /** - * @throws SPException - */ - public function testLoadUserMPassChangedPass() - { - $data = new UserLoginData(); - $data->setLoginUser('admin'); - $data->setLoginPass('debian'); - - /** @var UserLoginResponse $userData */ - $userData = self::$getUserLoginResponse->call($this, $data->getLoginUser()); - $userData->setIsChangedPass(true); - - $data->setUserLoginResponse($userData); - - $result = self::$service->loadUserMPass($data); - - $this->assertEquals(UserPassService::MPASS_CHECKOLD, $result->getStatus()); - } - - /** - * @throws SPException - */ - public function testLoadUserMPassNotSet() - { - $data = new UserLoginData(); - $data->setLoginUser('admin'); - $data->setLoginPass('debian'); - $data->setUserLoginResponse(new UserLoginResponse()); - - $result = self::$service->loadUserMPass($data); - - $this->assertEquals(UserPassService::MPASS_NOTSET, $result->getStatus()); - } - - /** - * @throws CryptoException - * @throws SPException - */ - public function testUpdateMasterPassOnLogin() - { - $data = new UserLoginData(); - $data->setLoginUser('admin'); - $data->setLoginPass('test123'); - $data->setUserLoginResponse(self::$getUserLoginResponse->call($this, $data->getLoginUser())); - - $result = self::$service->updateMasterPassOnLogin(self::CURRENT_MASTERPASS, $data); - - $this->assertEquals(UserPassService::MPASS_OK, $result->getStatus()); - - $result = self::$service->updateMasterPassOnLogin(self::NEW_MASTERPASS, $data); - - $this->assertEquals(UserPassService::MPASS_WRONG, $result->getStatus()); - } -} diff --git a/tests/SPT/Services/User/UserServiceTest.php b/tests/SPT/Services/User/UserServiceTest.php deleted file mode 100644 index 6a8d1119..00000000 --- a/tests/SPT/Services/User/UserServiceTest.php +++ /dev/null @@ -1,713 +0,0 @@ -. - */ - -namespace SPT\Services\User; - -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Core\Crypt\Hash; -use SP\DataModel\ItemSearchData; -use SP\DataModel\UserData; -use SP\DataModel\UserPreferencesData; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Config\Ports\ConfigDataInterface; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\User\Services\UserLoginRequest; -use SP\Domain\User\Services\UserService; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class UserServiceTest - * - * @package SPT\SP\Domain\User\Services - */ -class UserServiceTest extends DatabaseTestCase -{ - private const CURRENT_MASTERPASS = '12345678900'; - - /** - * @var ConfigDataInterface - */ - private static $configData; - - /** - * @var UserService - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - * @throws SPException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(UserService::class); - - self::$configData = $dic->get(ConfigDataInterface::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllBasic() - { - $data = self::$service->getAllBasic(); - - $this->assertCount(5, $data); - $this->assertInstanceOf(UserData::class, $data[0]); - $this->assertEquals('admin', $data[0]->getLogin()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUsageForUser() - { - $this->assertCount(2, self::$service->getUsageForUser(2)); - } - - /** - * @throws SPException - */ - public function testCreateOnLogin() - { - $data = new UserLoginRequest(); - $data->setName('Test SSO User'); - $data->setLogin('test_sso'); - $data->setEmail('test_sso@email.com'); - $data->setPassword('test123sso'); - - $result = self::$service->createOnLogin($data); - - $this->assertEquals(6, $result); - - /** @var UserData $resultData */ - $resultData = self::$service->getById($result); - - $this->assertEquals($data->getName(), $resultData->getName()); - $this->assertEquals($data->getLogin(), $resultData->getLogin()); - $this->assertEquals($data->getEmail(), $resultData->getEmail()); - $this->assertEquals(0, $resultData->isLdap()); - $this->assertTrue(Hash::checkHashKey($data->getPassword(), $resultData->getPass())); - $this->assertEquals(self::$configData->getSsoDefaultGroup(), $resultData->getUserGroupId()); - $this->assertEquals(self::$configData->getSsoDefaultProfile(), $resultData->getUserProfileId()); - - $data = new UserLoginRequest(); - $data->setName('Test LDAP User'); - $data->setLogin('test_ldap'); - $data->setEmail('test_ldap@email.com'); - $data->setPassword('test123ldap'); - $data->setIsLdap(true); - - $result = self::$service->createOnLogin($data); - - $this->assertEquals(7, $result); - - /** @var UserData $resultData */ - $resultData = self::$service->getById($result); - - $this->assertEquals($data->getName(), $resultData->getName()); - $this->assertEquals($data->getLogin(), $resultData->getLogin()); - $this->assertEquals($data->getEmail(), $resultData->getEmail()); - $this->assertEquals(1, $resultData->isLdap()); - $this->assertTrue(Hash::checkHashKey($data->getPassword(), $resultData->getPass())); - $this->assertEquals(self::$configData->getLdapDefaultGroup(), $resultData->getUserGroupId()); - $this->assertEquals(self::$configData->getLdapDefaultProfile(), $resultData->getUserProfileId()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - * @throws DuplicatedItemException - * @throws ServiceException - */ - public function testUpdate() - { - $data = new UserData(); - $data->setId(2); - $data->setName('Test User'); - $data->setLogin('test'); - $data->setEmail('test@syspass.org'); - $data->setNotes('Notes...'); - $data->setUserGroupId(3); - $data->setUserProfileId(3); - $data->setIsAdminApp(1); - $data->setIsAdminAcc(1); - $data->setIsDisabled(1); - $data->setIsChangePass(1); - $data->setIsLdap(0); - - self::$service->update($data); - - /** @var UserData $resultData */ - $resultData = self::$service->getById(2); - - $this->assertEquals($data->getName(), $resultData->getName()); - $this->assertEquals($data->getLogin(), $resultData->getLogin()); - $this->assertEquals($data->getEmail(), $resultData->getEmail()); - $this->assertEquals($data->getNotes(), $resultData->getNotes()); - $this->assertEquals($data->isLdap(), $resultData->isLdap()); - $this->assertEquals($data->getUserGroupId(), $resultData->getUserGroupId()); - $this->assertEquals($data->getUserProfileId(), $resultData->getUserProfileId()); - $this->assertEquals($data->isAdminApp(), $resultData->isAdminApp()); - $this->assertEquals($data->isAdminAcc(), $resultData->isAdminAcc()); - $this->assertEquals($data->isDisabled(), $resultData->isDisabled()); - $this->assertEquals($data->isChangePass(), $resultData->isChangePass()); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - * @throws DuplicatedItemException - * @throws ServiceException - */ - public function testUpdateDuplicatedLogin() - { - $data = new UserData(); - $data->setId(2); - $data->setName('Test User'); - $data->setLogin('user_a'); - $data->setEmail('test@syspass.org'); - $data->setNotes('Notes...'); - $data->setUserGroupId(3); - $data->setUserProfileId(3); - $data->setIsAdminApp(1); - $data->setIsAdminAcc(1); - $data->setIsDisabled(1); - $data->setIsChangePass(1); - $data->setIsLdap(0); - - $this->expectException(DuplicatedItemException::class); - - self::$service->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - * @throws DuplicatedItemException - * @throws ServiceException - */ - public function testUpdateDuplicatedEmail() - { - $data = new UserData(); - $data->setId(2); - $data->setName('Test User'); - $data->setLogin('test'); - $data->setEmail('user_a@syspass.org'); - $data->setNotes('Notes...'); - $data->setUserGroupId(3); - $data->setUserProfileId(3); - $data->setIsAdminApp(1); - $data->setIsAdminAcc(1); - $data->setIsDisabled(1); - $data->setIsChangePass(1); - $data->setIsLdap(0); - - $this->expectException(DuplicatedItemException::class); - - self::$service->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - * @throws DuplicatedItemException - * @throws ServiceException - */ - public function testUpdateUnknown() - { - $data = new UserData(); - $data->setId(10); - $data->setName('Test User'); - $data->setLogin('test'); - $data->setEmail('test@syspass.org'); - $data->setNotes('Notes...'); - $data->setUserGroupId(3); - $data->setUserProfileId(3); - $data->setIsAdminApp(1); - $data->setIsAdminAcc(1); - $data->setIsDisabled(1); - $data->setIsChangePass(1); - $data->setIsLdap(0); - - $this->expectException(ServiceException::class); - - self::$service->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - * @throws DuplicatedItemException - * @throws ServiceException - */ - public function testUpdateNull() - { - $data = new UserData(); - $data->setId(2); - - $this->expectException(ConstraintException::class); - - self::$service->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - * @throws SPException - */ - public function testUpdatePass() - { - self::$service->updatePass(2, 'test123'); - - $data = self::$service->getById(2); - - $this->assertTrue(Hash::checkHashKey('test123', $data->getPass())); - $this->assertEquals(0, $data->isChangePass()); - $this->assertEquals(1, $data->isChangedPass()); - - $this->expectException(ServiceException::class); - - self::$service->updatePass(10, 'test123'); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('User A'); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(1, $result->getNumRows()); - - $data = $result->getDataAsArray(); - - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(3, $data[0]->id); - $this->assertEquals('User A', $data[0]->name); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('test'); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $result->getDataAsArray()); - } - - /** - * @throws ConstraintException - * @throws ServiceException - * @throws QueryException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(2, self::$service->deleteByIdBatch([4, 5])); - - $this->expectException(ConstraintException::class); - - self::$service->deleteByIdBatch([1, 2]); - } - - /** - * @throws CryptoException - * @throws SPException - */ - public function testCreateWithMasterPass() - { - $data = new UserData(); - $data->setName('Test User'); - $data->setLogin('test'); - $data->setEmail('test@syspass.org'); - $data->setNotes('Test notes'); - $data->setUserGroupId(1); - $data->setUserProfileId(1); - $data->setIsAdminApp(1); - $data->setIsAdminAcc(1); - $data->setIsDisabled(1); - $data->setIsChangePass(1); - $data->setIsLdap(0); - - $result = self::$service->createWithMasterPass($data, 'test123', self::CURRENT_MASTERPASS); - - /** @var UserData $resultData */ - $resultData = self::$service->getById($result); - - $this->assertEquals($data->getName(), $resultData->getName()); - $this->assertEquals($data->getLogin(), $resultData->getLogin()); - $this->assertEquals($data->getEmail(), $resultData->getEmail()); - $this->assertEquals($data->getNotes(), $resultData->getNotes()); - $this->assertEquals($data->isLdap(), $resultData->isLdap()); - $this->assertEquals($data->getUserGroupId(), $resultData->getUserGroupId()); - $this->assertEquals($data->getUserProfileId(), $resultData->getUserProfileId()); - $this->assertEquals($data->isAdminApp(), $resultData->isAdminApp()); - $this->assertEquals($data->isAdminAcc(), $resultData->isAdminAcc()); - $this->assertEquals($data->isDisabled(), $resultData->isDisabled()); - $this->assertEquals($data->isChangePass(), $resultData->isChangePass()); - $this->assertEquals($data->isLdap(), $resultData->isLdap()); - $this->assertTrue(Hash::checkHashKey('test123', $resultData->getPass())); - $this->assertNotEmpty($resultData->getMPass()); - $this->assertNotEmpty($resultData->getMKey()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUserEmailForGroup() - { - $this->assertCount(4, self::$service->getUserEmailForGroup(2)); - - $this->assertCount(0, self::$service->getUserEmailForGroup(10)); - } - - /** - * @throws SPException - */ - public function testGetByLogin() - { - $data = self::$service->getByLogin('demo'); - - $this->assertInstanceOf(UserData::class, $data); - $this->assertEquals('sysPass demo', $data->getName()); - $this->assertEquals('demo', $data->getLogin()); - $this->assertEquals('demo', $data->getSsoLogin()); - $this->assertEquals('demo@syspass.org', $data->getEmail()); - $this->assertEquals('aaaa', $data->getNotes()); - $this->assertEquals('2018-04-01 21:29:47', $data->getLastLogin()); - $this->assertEquals('2018-04-14 08:47:43', $data->getLastUpdate()); - $this->assertEquals(1522582852, $data->getLastUpdateMPass()); - $this->assertEquals('Demo', $data->getUserGroupName()); - $this->assertEquals(2, $data->getUserGroupId()); - $this->assertEquals(2, $data->getUserProfileId()); - $this->assertEquals(0, $data->isAdminApp()); - $this->assertEquals(0, $data->isAdminAcc()); - $this->assertEquals(0, $data->isLdap()); - $this->assertEquals(0, $data->isDisabled()); - $this->assertEquals(0, $data->isMigrate()); - $this->assertEquals(0, $data->isChangePass()); - $this->assertEquals(0, $data->isChangedPass()); - $this->assertNotEmpty($data->getPass()); - $this->assertNotEmpty($data->getMPass()); - $this->assertNotEmpty($data->getMKey()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getByLogin('test'); - } - - /** - * @throws SPException - */ - public function testCreate() - { - $data = new UserData(); - $data->setName('Test User'); - $data->setLogin('test'); - $data->setEmail('test@syspass.org'); - $data->setNotes('Test notes'); - $data->setUserGroupId(1); - $data->setUserProfileId(1); - $data->setIsAdminApp(1); - $data->setIsAdminAcc(1); - $data->setIsDisabled(1); - $data->setIsChangePass(1); - $data->setIsLdap(0); - $data->setPass('test123'); - - $result = self::$service->create($data); - - /** @var UserData $resultData */ - $resultData = self::$service->getById($result); - - $this->assertEquals($data->getName(), $resultData->getName()); - $this->assertEquals($data->getLogin(), $resultData->getLogin()); - $this->assertEquals($data->getEmail(), $resultData->getEmail()); - $this->assertEquals($data->getNotes(), $resultData->getNotes()); - $this->assertEquals($data->isLdap(), $resultData->isLdap()); - $this->assertEquals($data->getUserGroupId(), $resultData->getUserGroupId()); - $this->assertEquals($data->getUserProfileId(), $resultData->getUserProfileId()); - $this->assertEquals($data->isAdminApp(), $resultData->isAdminApp()); - $this->assertEquals($data->isAdminAcc(), $resultData->isAdminAcc()); - $this->assertEquals($data->isDisabled(), $resultData->isDisabled()); - $this->assertEquals($data->isChangePass(), $resultData->isChangePass()); - $this->assertEquals($data->isLdap(), $resultData->isLdap()); - $this->assertTrue(Hash::checkHashKey('test123', $resultData->getPass())); - $this->assertNull($data->getMPass()); - $this->assertNull($data->getMKey()); - } - - /** - * @throws SPException - */ - public function testCreateDuplicatedLogin() - { - $data = new UserData(); - $data->setName('Test User'); - $data->setLogin('demo'); - $data->setEmail('test@syspass.org'); - $data->setNotes('Test notes'); - $data->setUserGroupId(1); - $data->setUserProfileId(1); - $data->setIsAdminApp(1); - $data->setIsAdminAcc(1); - $data->setIsDisabled(1); - $data->setIsChangePass(1); - $data->setIsLdap(0); - $data->setPass('test123'); - - $this->expectException(DuplicatedItemException::class); - - self::$service->create($data); - } - - /** - * @throws SPException - */ - public function testCreateDuplicatedEmail() - { - $data = new UserData(); - $data->setName('Test User'); - $data->setLogin('test'); - $data->setEmail('demo@syspass.org'); - $data->setNotes('Test notes'); - $data->setUserGroupId(1); - $data->setUserProfileId(1); - $data->setIsAdminApp(1); - $data->setIsAdminAcc(1); - $data->setIsDisabled(1); - $data->setIsChangePass(1); - $data->setIsLdap(0); - $data->setPass('test123'); - - $this->expectException(DuplicatedItemException::class); - - self::$service->create($data); - } - - /** - * @throws SPException - */ - public function testCreateNull() - { - $data = new UserData(); - $data->setName('Test User'); - $data->setNotes('Test notes'); - $data->setUserGroupId(1); - $data->setUserProfileId(1); - $data->setIsAdminApp(1); - $data->setIsAdminAcc(1); - $data->setIsDisabled(1); - $data->setIsChangePass(1); - $data->setIsLdap(0); - $data->setPass('test123'); - - $this->expectException(ConstraintException::class); - - self::$service->create($data); - } - - /** - * @throws SPException - */ - public function testGetById() - { - $data = self::$service->getById(2); - - $this->assertInstanceOf(UserData::class, $data); - $this->assertEquals('sysPass demo', $data->getName()); - $this->assertEquals('demo', $data->getLogin()); - $this->assertEquals('demo', $data->getSsoLogin()); - $this->assertEquals('demo@syspass.org', $data->getEmail()); - $this->assertEquals('aaaa', $data->getNotes()); - $this->assertEquals('2018-04-01 21:29:47', $data->getLastLogin()); - $this->assertEquals('2018-04-14 08:47:43', $data->getLastUpdate()); - $this->assertEquals(1522582852, $data->getLastUpdateMPass()); - $this->assertEquals('Demo', $data->getUserGroupName()); - $this->assertEquals(2, $data->getUserGroupId()); - $this->assertEquals(2, $data->getUserProfileId()); - $this->assertEquals(0, $data->isAdminApp()); - $this->assertEquals(0, $data->isAdminAcc()); - $this->assertEquals(0, $data->isLdap()); - $this->assertEquals(0, $data->isDisabled()); - $this->assertEquals(0, $data->isMigrate()); - $this->assertEquals(0, $data->isChangePass()); - $this->assertEquals(0, $data->isChangedPass()); - $this->assertNotEmpty($data->getPass()); - $this->assertNotEmpty($data->getMPass()); - $this->assertNotEmpty($data->getMKey()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getById(10); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdatePreferencesById() - { - $data = new UserPreferencesData(); - $data->setLang('es_ES'); - $data->setAccountLink(true); - $data->setOptionalActions(true); - $data->setResultsAsCards(true); - $data->setResultsPerPage(10); - $data->setTopNavbar(true); - $data->setTheme('theme'); - - $this->assertEquals(1, self::$service->updatePreferencesById(2, $data)); - - $resultData = self::$service->getById(2); - - $this->assertNotEmpty($resultData->getPreferences()); - - $this->assertEquals($data, UserService::getUserPreferences($resultData->getPreferences())); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testUpdateLastLoginById() - { - $this->assertEquals(1, self::$service->updateLastLoginById(2)); - - $this->expectException(NoSuchItemException::class); - - $this->assertEquals(0, self::$service->updateLastLoginById(10)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCheckExistsByLogin() - { - $this->assertTrue(self::$service->checkExistsByLogin('demo')); - - $this->assertFalse(self::$service->checkExistsByLogin('test')); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDelete() - { - self::$service->delete(4); - - $this->assertEquals(4, self::getRowCount('User')); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDeleteUsed() - { - $this->expectException(ConstraintException::class); - - self::$service->delete(1); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testDeleteUnknown() - { - $this->expectException(NoSuchItemException::class); - - self::$service->delete(10); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdateOnLogin() - { - $data = new UserLoginRequest(); - $data->setName('prueba'); - $data->setEmail('prueba@syspass.org'); - $data->setIsLdap(true); - $data->setLogin('demo'); - $data->setPassword('test123'); - - $this->assertEquals(1, self::$service->updateOnLogin($data)); - - /** @var UserData $resultData */ - $resultData = self::$service->getByLogin('demo'); - - $this->assertEquals($data->getName(), $resultData->getName()); - $this->assertEquals($data->getLogin(), $resultData->getLogin()); - $this->assertEquals($data->getEmail(), $resultData->getEmail()); - $this->assertEquals($data->getisLdap(), $resultData->isLdap()); - $this->assertTrue(Hash::checkHashKey($data->getPassword(), $resultData->getPass())); - - $data->setLogin('demodedadae'); - - $this->assertEquals(0, self::$service->updateOnLogin($data)); - } -} diff --git a/tests/SPT/Services/UserGroup/UserGroupServiceTest.php b/tests/SPT/Services/UserGroup/UserGroupServiceTest.php deleted file mode 100644 index f493bb59..00000000 --- a/tests/SPT/Services/UserGroup/UserGroupServiceTest.php +++ /dev/null @@ -1,325 +0,0 @@ -. - */ - -namespace SPT\Services\UserGroup; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemSearchData; -use SP\DataModel\UserGroupData; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\User\Ports\UserGroupServiceInterface; -use SP\Domain\User\Services\UserGroupService; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class UserGroupServiceTest - * - * @package SPT\SP\Domain\Common\Services\UserGroup - */ -class UserGroupServiceTest extends DatabaseTestCase -{ - - /** - * @var UserGroupServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - * @throws SPException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(UserGroupService::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllBasic() - { - $data = self::$service->getAllBasic(); - - $this->assertCount(6, $data); - - $this->assertInstanceOf(UserGroupData::class, $data[0]); - $this->assertEquals('Admins', $data[0]->getName()); - $this->assertEquals('sysPass Admins', $data[0]->getDescription()); - - $this->assertInstanceOf(UserGroupData::class, $data[1]); - $this->assertEquals('Demo', $data[1]->getName()); - $this->assertEmpty($data[1]->getDescription()); - } - - /** - * @throws SPException - */ - public function testDelete() - { - self::$service->delete(5); - - $this->assertEquals(5, self::getRowCount('UserGroup')); - } - - /** - * @throws SPException - */ - public function testDeleteUsed() - { - $this->expectException(ConstraintException::class); - - self::$service->delete(1); - } - - /** - * @throws SPException - */ - public function testDeleteUnknown() - { - $this->expectException(NoSuchItemException::class); - - self::$service->delete(10); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(2, self::$service->deleteByIdBatch([5, 6])); - - $this->assertEquals(4, self::getRowCount('UserGroup')); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testDeleteByIdBatchUsed() - { - // Se lanza excepción en caso de restricción relacional - $this->expectException(ConstraintException::class); - - self::$service->deleteByIdBatch([1, 2]); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testDeleteByIdBatchUnknown() - { - $this->expectException(ServiceException::class); - - self::$service->deleteByIdBatch([5, 6, 10]); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdate() - { - $data = new UserGroupData(); - $data->setId(2); - $data->setName('Test group'); - $data->setDescription('Group for demo users'); - $data->setUsers([2]); - - self::$service->update($data); - - $this->assertEquals($data, self::$service->getById(2)); - } - - /** - * @throws ServiceException - */ - public function testUpdateDuplicated() - { - $data = new UserGroupData(); - $data->setId(2); - $data->setName('Admins'); - - $this->expectException(DuplicatedItemException::class); - - self::$service->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUsage() - { - $this->assertCount(7, self::$service->getUsage(2)); - - $this->assertCount(3, self::$service->getUsage(3)); - - $this->assertCount(1, self::$service->getUsage(4)); - - $this->assertCount(0, self::$service->getUsage(5)); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws ServiceException - * @throws QueryException - */ - public function testCreate() - { - $data = new UserGroupData(); - $data->setId(7); - $data->setName('Test group'); - $data->setDescription('Group for demo users'); - $data->setUsers([2]); - - $this->assertEquals($data->getId(), self::$service->create($data)); - - $this->assertEquals($data, self::$service->getById($data->getId())); - } - - /** - * @throws ServiceException - */ - public function testCreateDuplicated() - { - $data = new UserGroupData(); - $data->setName('Admins'); - $data->setDescription('Group for demo users'); - - $this->expectException(DuplicatedItemException::class); - - self::$service->create($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Demo'); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(UserGroupData::class, $data[0]); - $this->assertEquals(2, $data[0]->id); - $this->assertEquals('Demo', $data[0]->name); - $this->assertEmpty($data[0]->description); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('test'); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(3, $result->getNumRows()); - - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('aa'); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetByName() - { - $data = self::$service->getByName('Demo'); - - $this->assertInstanceOf(UserGroupData::class, $data); - $this->assertEquals('Demo', $data->getName()); - $this->assertEmpty($data->getDescription()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getByName('Test'); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testGetById() - { - $data = self::$service->getById(2); - - $this->assertInstanceOf(UserGroupData::class, $data); - $this->assertEquals('Demo', $data->getName()); - $this->assertEmpty($data->getDescription()); - - - $this->expectException(NoSuchItemException::class); - - self::$service->getById(10); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUsageByUsers() - { - $this->assertCount(2, self::$service->getUsageByUsers(1)); - - $this->assertCount(5, self::$service->getUsageByUsers(2)); - - $this->assertCount(0, self::$service->getUsageByUsers(5)); - } -} diff --git a/tests/SPT/Services/UserGroup/UserToUserGroupServiceTest.php b/tests/SPT/Services/UserGroup/UserToUserGroupServiceTest.php deleted file mode 100644 index 293fbd37..00000000 --- a/tests/SPT/Services/UserGroup/UserToUserGroupServiceTest.php +++ /dev/null @@ -1,194 +0,0 @@ -. - */ - -namespace SPT\Services\UserGroup; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\UserToUserGroupData; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\User\Ports\UserToUserGroupServiceInterface; -use SP\Domain\User\Services\UserToUserGroupService; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class UserToUserGroupServiceTest - * - * @package SPT\SP\Domain\Common\Services\UserGroup - */ -class UserToUserGroupServiceTest extends DatabaseTestCase -{ - - /** - * @var UserToUserGroupServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - * @throws SPException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(UserToUserGroupService::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testCheckUserInGroup() - { - $this->assertTrue(self::$service->checkUserInGroup(1, 2)); - - $this->assertTrue(self::$service->checkUserInGroup(2, 3)); - - $this->assertFalse(self::$service->checkUserInGroup(3, 3)); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetGroupsForUser() - { - $data = self::$service->getGroupsForUser(3); - - $this->assertCount(1, $data); - $this->assertEquals(2, $data[0]->userGroupId); - - $data = self::$service->getGroupsForUser(2); - - $this->assertCount(1, $data); - $this->assertEquals(1, $data[0]->userGroupId); - - $data = self::$service->getGroupsForUser(10); - - $this->assertCount(0, $data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testAdd() - { - $data = [3, 4]; - - self::$service->add(1, $data); - - $this->assertEquals([2, 3, 4], self::$service->getUsersByGroupId(1)); - - $this->expectException(ConstraintException::class); - - self::$service->add(10, $data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testAddDuplicated() - { - $data = [2, 3, 4]; - - $this->expectException(ConstraintException::class); - - self::$service->add(1, $data); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testUpdate() - { - $data = [3, 4]; - - self::$service->update(1, $data); - - $this->assertEquals($data, self::$service->getUsersByGroupId(1)); - - $this->expectException(ConstraintException::class); - - self::$service->update(10, $data); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testGetById() - { - $data = self::$service->getById(2); - - $this->assertCount(2, $data); - - $this->assertInstanceOf(UserToUserGroupData::class, $data[0]); - - $this->assertEquals(2, $data[0]->getUserGroupId()); - $this->assertEquals(1, $data[0]->getUserId()); - - $this->assertEquals(2, $data[1]->getUserGroupId()); - $this->assertEquals(3, $data[1]->getUserId()); - - $data = self::$service->getById(1); - - $this->assertCount(1, $data); - - $this->assertEquals(1, $data[0]->getUserGroupId()); - $this->assertEquals(2, $data[0]->getUserId()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getById(10); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUsersByGroupId() - { - $data = self::$service->getUsersByGroupId(2); - - $this->assertCount(2, $data); - - $this->assertEquals([1, 3], $data); - } -} diff --git a/tests/SPT/Services/UserPassRecover/UserPassRecoverServiceTest.php b/tests/SPT/Services/UserPassRecover/UserPassRecoverServiceTest.php deleted file mode 100644 index a45eba3e..00000000 --- a/tests/SPT/Services/UserPassRecover/UserPassRecoverServiceTest.php +++ /dev/null @@ -1,165 +0,0 @@ -. - */ - -namespace SPT\Services\UserPassRecover; - -use Defuse\Crypto\Exception\EnvironmentIsBrokenException; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\User\Ports\UserPassRecoverServiceInterface; -use SP\Domain\User\Services\UserPassRecoverService; -use SP\Util\PasswordUtil; -use SPT\DatabaseTestCase; - -use function SPT\setupContext; - -/** - * Class UserPassRecoverServiceTest - * - * @package SPT\SP\Domain\Common\Services\UserPassRecover - */ -class UserPassRecoverServiceTest extends DatabaseTestCase -{ - /** - * @var UserPassRecoverServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - * @throws SPException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(UserPassRecoverService::class); - } - - /** - * @throws ConstraintException - * @throws ServiceException - * @throws EnvironmentIsBrokenException - * @throws QueryException - * @throws SPException - */ - public function testToggleUsedByHash() - { - self::$service->toggleUsedByHash(self::$service->requestForUserId(2)); - - $this->expectException(ServiceException::class); - - self::$service->toggleUsedByHash(PasswordUtil::generateRandomBytes()); - } - - /** - * @throws ServiceException - * @throws SPException - */ - public function testToggleUsedByHashExpired() - { - $this->expectException(ServiceException::class); - - self::$service->toggleUsedByHash(pack('H*', '3038366162313036303866363838346566383031396134353237333561633066')); - } - - /** - * @throws ConstraintException - * @throws EnvironmentIsBrokenException - * @throws QueryException - */ - public function testAdd() - { - $this->assertEquals(3, self::$service->add(2, PasswordUtil::generateRandomBytes())); - - $this->expectException(ConstraintException::class); - - self::$service->add(10, PasswordUtil::generateRandomBytes()); - } - - /** - * @throws ConstraintException - * @throws ServiceException - * @throws EnvironmentIsBrokenException - * @throws QueryException - */ - public function testRequestForUserId() - { - $hash = self::$service->requestForUserId(2); - - $this->assertNotEmpty($hash); - - $this->assertEquals(2, self::$service->getUserIdForHash($hash)); - - $this->expectException(ConstraintException::class); - - self::$service->requestForUserId(10); - } - - /** - * @throws ConstraintException - * @throws ServiceException - * @throws EnvironmentIsBrokenException - * @throws QueryException - */ - public function testCheckAttemptsByUserId() - { - $this->assertFalse(self::$service->checkAttemptsByUserId(2)); - - for ($i = 1; $i <= UserPassRecoverService::MAX_PASS_RECOVER_LIMIT; $i++) { - self::$service->requestForUserId(2); - } - - $this->assertTrue(self::$service->checkAttemptsByUserId(2)); - - $this->assertFalse(self::$service->checkAttemptsByUserId(10)); - } - - /** - * @throws ConstraintException - * @throws EnvironmentIsBrokenException - * @throws QueryException - * @throws ServiceException - */ - public function testGetUserIdForHash() - { - $result = self::$service->getUserIdForHash(self::$service->requestForUserId(2)); - - $this->assertEquals(2, $result); - - $this->expectException(ServiceException::class); - - self::$service->getUserIdForHash(PasswordUtil::generateRandomBytes()); - } -} diff --git a/tests/SPT/Services/UserProfile/UserProfileServiceTest.php b/tests/SPT/Services/UserProfile/UserProfileServiceTest.php deleted file mode 100644 index 2440eb7c..00000000 --- a/tests/SPT/Services/UserProfile/UserProfileServiceTest.php +++ /dev/null @@ -1,290 +0,0 @@ -. - */ - -namespace SPT\Services\UserProfile; - -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Context\ContextException; -use SP\DataModel\ItemSearchData; -use SP\DataModel\ProfileData; -use SP\DataModel\UserProfileData; -use SP\Domain\Common\Services\ServiceException; -use SP\Domain\Core\Exceptions\ConstraintException; -use SP\Domain\Core\Exceptions\QueryException; -use SP\Domain\Core\Exceptions\SPException; -use SP\Domain\User\Ports\UserProfileServiceInterface; -use SP\Domain\User\Services\UserProfileService; -use SP\Infrastructure\Common\Repositories\DuplicatedItemException; -use SP\Infrastructure\Common\Repositories\NoSuchItemException; -use SPT\DatabaseTestCase; -use stdClass; - -use function SPT\setupContext; - -/** - * Class UserProfileServiceTest - * - * @package SPT\SP\Domain\Common\Services\UserProfile - */ -class UserProfileServiceTest extends DatabaseTestCase -{ - /** - * @var UserProfileServiceInterface - */ - private static $service; - - /** - * @throws NotFoundException - * @throws ContextException - * @throws DependencyException - * @throws SPException - */ - public static function setUpBeforeClass(): void - { - $dic = setupContext(); - - self::$loadFixtures = true; - - // Inicializar el servicio - self::$service = $dic->get(UserProfileService::class); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testSearch() - { - $itemSearchData = new ItemSearchData(); - $itemSearchData->setLimitCount(10); - $itemSearchData->setSeachString('Demo'); - - $result = self::$service->search($itemSearchData); - $data = $result->getDataAsArray(); - - $this->assertEquals(1, $result->getNumRows()); - $this->assertCount(1, $data); - $this->assertInstanceOf(stdClass::class, $data[0]); - $this->assertEquals(2, $data[0]->id); - $this->assertEquals('Demo', $data[0]->name); - - // Nueva búsqueda de perfil no existente - $itemSearchData->setSeachString('prueba'); - - $result = self::$service->search($itemSearchData); - - $this->assertEquals(0, $result->getNumRows()); - $this->assertCount(0, $result->getDataAsArray()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetAllBasic() - { - $data = self::$service->getAllBasic(); - - $this->assertCount(3, $data); - - $this->assertInstanceOf(UserProfileData::class, $data[0]); - $this->assertEquals('Admin', $data[0]->getName()); - - $this->assertInstanceOf(UserProfileData::class, $data[1]); - $this->assertEquals('Demo', $data[1]->getName()); - } - - /** - * @throws ConstraintException - * @throws QueryException - */ - public function testGetUsersForProfile() - { - $this->assertCount(1, self::$service->getUsersForProfile(2)); - - $this->assertCount(0, self::$service->getUsersForProfile(3)); - - $this->assertCount(0, self::$service->getUsersForProfile(10)); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdate() - { - $data = new UserProfileData(); - $data->setId(2); - $data->setName('Test Profile'); - - self::$service->update($data); - - $this->assertTrue(true); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdateUnknown() - { - $data = new UserProfileData(); - $data->setId(10); - $data->setName('Test Profile'); - - $this->expectException(ServiceException::class); - - self::$service->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws SPException - */ - public function testUpdateDuplicated() - { - $data = new UserProfileData(); - $data->setId(2); - $data->setName('Admin'); - - $this->expectException(DuplicatedItemException::class); - - self::$service->update($data); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testDeleteByIdBatch() - { - $this->assertEquals(1, self::$service->deleteByIdBatch([3])); - - $this->assertEquals(2, self::getRowCount('UserProfile')); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testDeleteByIdBatchUsed() - { - $this->expectException(ConstraintException::class); - - self::$service->deleteByIdBatch([1, 2]); - - $this->assertEquals(3, self::getRowCount('UserProfile')); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws ServiceException - */ - public function testDeleteByIdBatchUnknown() - { - $this->expectException(ServiceException::class); - - self::$service->deleteByIdBatch([3, 10]); - - $this->assertEquals(2, self::getRowCount('UserProfile')); - } - - /** - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - */ - public function testGetById() - { - $result = self::$service->getById(2); - - $this->assertInstanceOf(UserProfileData::class, $result); - $this->assertInstanceOf(ProfileData::class, $result->getProfile()); - - $this->expectException(NoSuchItemException::class); - - self::$service->getById(10); - } - - /** - * @throws ConstraintException - * @throws NoSuchItemException - * @throws QueryException - */ - public function testDelete() - { - self::$service->delete(3); - - $this->assertEquals(2, self::getRowCount('UserProfile')); - - $this->expectException(ConstraintException::class); - - self::$service->delete(1); - } - - /** - * @throws SPException - */ - public function testCreate() - { - $profileData = new ProfileData(); - $profileData->setAccAdd(true); - $profileData->setAccDelete(true); - $profileData->setConfigBackup(true); - - $data = new UserProfileData(); - $data->setId(4); - $data->setName('Prueba'); - $data->setProfile($profileData); - - $result = self::$service->create($data); - - $this->assertEquals($data->getId(), $result); - - $this->assertEquals(4, self::getRowCount('UserProfile')); - - $this->assertEquals($data, self::$service->getById($result)); - } - - /** - * @throws SPException - */ - public function testCreateDuplicated() - { - $data = new UserProfileData(); - $data->setName('Admin'); - $data->setProfile(new ProfileData()); - - $this->expectException(DuplicatedItemException::class); - - self::$service->create($data); - } -} diff --git a/tests/SPT/Storage/ArchiveHandlerTest.php b/tests/SPT/Storage/ArchiveHandlerTest.php deleted file mode 100644 index 514f4db4..00000000 --- a/tests/SPT/Storage/ArchiveHandlerTest.php +++ /dev/null @@ -1,108 +0,0 @@ -. - */ - -namespace SPT\Storage; - -use PHPUnit\Framework\TestCase; -use RuntimeException; -use SP\Core\PhpExtensionChecker; -use SP\Domain\Core\Exceptions\CheckException; -use SP\Infrastructure\File\ArchiveHandler; -use SP\Infrastructure\File\FileException; -use UnexpectedValueException; - -/** - * Class ArchiveHandlerTest - * - * @package SPT\Storage - */ -class ArchiveHandlerTest extends TestCase -{ - public const ARCHIVE = TMP_PATH . DIRECTORY_SEPARATOR . 'test_archive'; - - /** - * @throws CheckException - * @throws FileException - */ - public function testCompressFile() - { - $archive = TMP_PATH . DIRECTORY_SEPARATOR . 'test_archive_file'; - - $handler = new ArchiveHandler($archive, new PhpExtensionChecker()); - $handler->compressFile(RESOURCE_PATH . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.xml'); - - $this->assertFileExists($archive . ArchiveHandler::COMPRESS_EXTENSION); - } - - /** - * @throws CheckException - * @throws FileException - */ - public function testCompressInvalidFile() - { - $this->expectException(RuntimeException::class); - - $archive = TMP_PATH . DIRECTORY_SEPARATOR . 'test_archive_file'; - - $handler = new ArchiveHandler($archive, new PhpExtensionChecker()); - $handler->compressFile(RESOURCE_PATH . DIRECTORY_SEPARATOR . 'non_existant_file'); - } - - /** - * @throws CheckException - * @throws FileException - */ - public function testCompressDirectory() - { - $archive = TMP_PATH . DIRECTORY_SEPARATOR . 'test_archive_dir'; - - $handler = new ArchiveHandler($archive, new PhpExtensionChecker()); - $handler->compressDirectory(RESOURCE_PATH); - - $this->assertFileExists($archive . ArchiveHandler::COMPRESS_EXTENSION); - } - - /** - * @throws CheckException - * @throws FileException - */ - public function testCompressInvalidDirectory() - { - $this->expectException(UnexpectedValueException::class); - - $archive = TMP_PATH . DIRECTORY_SEPARATOR . 'test_archive_dir'; - - $handler = new ArchiveHandler($archive, new PhpExtensionChecker()); - $handler->compressDirectory(RESOURCE_PATH . DIRECTORY_SEPARATOR . 'non_existant_dir'); - } - - /** - * Sets up the fixture, for example, open a network connection. - * This method is called before a test is executed. - */ - protected function setUp(): void - { - array_map('unlink', glob(TMP_PATH . DIRECTORY_SEPARATOR . 'test_archive_*')); - } -} diff --git a/tests/SPT/Storage/FileCachePackedTest.php b/tests/SPT/Storage/FileCachePackedTest.php deleted file mode 100644 index 17296f21..00000000 --- a/tests/SPT/Storage/FileCachePackedTest.php +++ /dev/null @@ -1,137 +0,0 @@ -. - */ - -namespace SPT\Storage; - -use Faker\Factory; -use PHPUnit\Framework\TestCase; -use SP\Infrastructure\File\FileCachePacked; -use SP\Infrastructure\File\FileException; -use stdClass; - -/** - * Class FileCachePackedTest - * - * @package SPT\Storage - */ -class FileCachePackedTest extends TestCase -{ - public const CACHE_FILE = TMP_PATH . DIRECTORY_SEPARATOR . 'test_packed.cache'; - - private static $data; - - /** - * This method is called before the first test of this test class is run. - */ - public static function setUpBeforeClass(): void - { - self::$data = []; - $i = 0; - - $faker = Factory::create(); - - do { - $data = new stdClass(); - $data->id = uniqid(); - $data->name = $faker->name; - $data->values = [1, 2, 3]; - $data->object = new stdClass(); - $data->object->uid = uniqid(); - $data->object->type = $faker->address; - $data->object->notes = $faker->text; - - self::$data[] = $data; - - $i++; - } while ($i < 100); - } - - /** - * @throws FileException - */ - public function testDeleteInvalid() - { - $this->expectNotToPerformAssertions(); - - $cache = new FileCachePacked(self::CACHE_FILE); - $cache->delete(); - } - - /** - * @throws FileException - */ - public function testSave() - { - $cache = new FileCachePacked(self::CACHE_FILE); - $cache->save(self::$data); - - $this->assertFileExists(self::CACHE_FILE); - } - - /** - * @throws FileException - */ - public function testLoad() - { - $cache = new FileCachePacked(self::CACHE_FILE); - $data = $cache->load(); - - $this->assertEquals(self::$data, $data); - } - - /** - * @throws FileException - */ - public function testIsExpired() - { - // Sleep for 3 seconds before checking whether is expired - sleep(3); - - $cache = new FileCachePacked(self::CACHE_FILE); - $this->assertTrue($cache->isExpired(2)); - } - - /** - * @throws FileException - */ - public function testIsExpiredDate() - { - // Sleep for 3 seconds before checking whether is expired - sleep(3); - - $cache = new FileCachePacked(self::CACHE_FILE); - $this->assertTrue($cache->isExpiredDate(time())); - } - - /** - * @throws FileException - */ - public function testDelete() - { - $cache = new FileCachePacked(self::CACHE_FILE); - $cache->delete(); - - $this->assertTrue(true); - } -} diff --git a/tests/SPT/Storage/FileCacheTest.php b/tests/SPT/Storage/FileCacheTest.php deleted file mode 100644 index ff7208b8..00000000 --- a/tests/SPT/Storage/FileCacheTest.php +++ /dev/null @@ -1,137 +0,0 @@ -. - */ - -namespace SPT\Storage; - -use Faker\Factory; -use PHPUnit\Framework\TestCase; -use SP\Infrastructure\File\FileCache; -use SP\Infrastructure\File\FileException; -use stdClass; - -/** - * Class FileCacheTest - * - * @package SPT\Storage - */ -class FileCacheTest extends TestCase -{ - public const CACHE_FILE = TMP_PATH . DIRECTORY_SEPARATOR . 'test.cache'; - - private static $data; - - /** - * This method is called before the first test of this test class is run. - */ - public static function setUpBeforeClass(): void - { - self::$data = []; - $i = 0; - - $faker = Factory::create(); - - do { - $data = new stdClass(); - $data->id = uniqid(); - $data->name = $faker->name; - $data->values = [1, 2, 3]; - $data->object = new stdClass(); - $data->object->uid = uniqid(); - $data->object->type = $faker->address; - $data->object->notes = $faker->text; - - self::$data[] = $data; - - $i++; - } while ($i < 100); - } - - /** - * @throws FileException - */ - public function testDeleteInvalid() - { - $this->expectNotToPerformAssertions(); - - $cache = new FileCache(self::CACHE_FILE); - $cache->delete(); - } - - /** - * @throws FileException - */ - public function testSave() - { - $cache = new FileCache(self::CACHE_FILE); - $cache->save(self::$data); - - $this->assertFileExists(self::CACHE_FILE); - } - - /** - * @throws FileException - */ - public function testLoad() - { - $cache = new FileCache(self::CACHE_FILE); - $data = $cache->load(); - - $this->assertEquals(self::$data, $data); - } - - /** - * @throws FileException - */ - public function testIsExpired() - { - // Sleep for 3 seconds before checking whether is expired - sleep(3); - - $cache = new FileCache(self::CACHE_FILE); - $this->assertTrue($cache->isExpired(2)); - } - - /** - * @throws FileException - */ - public function testIsExpiredDate() - { - // Sleep for 3 seconds before checking whether is expired - sleep(3); - - $cache = new FileCache(self::CACHE_FILE); - $this->assertTrue($cache->isExpiredDate(time())); - } - - /** - * @throws FileException - */ - public function testDelete() - { - $cache = new FileCache(self::CACHE_FILE); - $cache->delete(); - - $this->assertTrue(true); - } -} diff --git a/tests/SPT/Storage/FileHandlerTest.php b/tests/SPT/Storage/FileHandlerTest.php deleted file mode 100644 index a0bd998c..00000000 --- a/tests/SPT/Storage/FileHandlerTest.php +++ /dev/null @@ -1,179 +0,0 @@ -. - */ - -namespace SPT\Storage; - -use PHPUnit\Framework\TestCase; -use SP\Infrastructure\File\FileException; -use SP\Infrastructure\File\FileHandler; - -/** - * Class FileHandlerTest - * - * Tests unitarios para comprobar el funcionamiento de la clase SP\Infrastructure\File\FileHandler - * - * @package SPT - */ -class FileHandlerTest extends TestCase -{ - /** - * @var string Archvivo de prueba válido - */ - protected static $validFile = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'valid_file.test'; - /** - * @var string Archvivo de prueba inmutable - */ - protected static $immutableFile = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'immutable_file.test'; - /** - * @var string Archivo de prueba no existente - */ - protected static $missingFile = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'missing_file.test'; - - /** - * Comprobar la escritura de texto en un archivo - * - * @throws FileException - */ - public function testWrite() - { - $handler = new FileHandler(self::$validFile); - $handler->write('valid_file'); - - $this->assertEquals('valid_file', $handler->readToString()); - - $handler->close(); - - $this->assertFileExists(self::$validFile); - } - - /** - * Comprobar si es posible escribir en el archivo - * - * @throws FileException - */ - public function testCheckIsWritable() - { - (new FileHandler(self::$validFile)) - ->clearCache() - ->checkIsWritable(); - - $this->assertTrue(true); - } - - /** - * Comprobar el tamaño del archivo - * - * @throws FileException - */ - public function testGetFileSize() - { - $size = (new FileHandler(self::$validFile))->getFileSize(); - - $this->assertEquals(10, $size); - } - - /** - * Comprobar un archivo válido - * - * @throws FileException - */ - public function testCheckFileExists() - { - $this->markTestSkipped(); - - (new FileHandler(self::$validFile)) - ->clearCache() - ->checkFileExists(); - - $this->assertTrue(true); - } - - /** - * Comprobar un archivo válido - * - * @throws FileException - */ - public function testCheckFileDoesNotExists() - { - $this->expectException(FileException::class); - - (new FileHandler(self::$missingFile)) - ->clearCache() - ->checkFileExists(); - } - - /** - * Abrir un archivo - * - * @throws FileException - */ - public function testOpenAndRead() - { - $handler = new FileHandler(self::$validFile); - $handler->open('rb'); - $this->assertEquals('valid_file', $handler->read()); - $this->assertEquals('valid_file', $handler->readToString()); - } - - /** - * Comprobar a cerrar un archivo - * - * @throws FileException - */ - public function testClose() - { - $handler = new FileHandler(self::$validFile); - $handler->open('rb'); - $handler->close(); - - $this->expectException(FileException::class); - $handler->close(); - } - - /** - * Comprobar si es posible leer el archivo - * - * @throws FileException - */ - public function testCheckIsReadable() - { - (new FileHandler(self::$validFile)) - ->clearCache() - ->checkIsReadable(); - - $this->assertTrue(true); - } - - /** - * Comprobar la eliminación de un archivo - * - * @throws FileException - */ - public function testDelete() - { - (new FileHandler(self::$validFile))->delete(); - - $this->assertFileDoesNotExist(self::$validFile); - } -} diff --git a/tests/SPT/Storage/XmlHandlerTest.php b/tests/SPT/Storage/XmlHandlerTest.php deleted file mode 100644 index da9b03fe..00000000 --- a/tests/SPT/Storage/XmlHandlerTest.php +++ /dev/null @@ -1,120 +0,0 @@ -. - */ - -namespace SPT\Storage; - -use PHPUnit\Framework\TestCase; -use RuntimeException; -use SP\Infrastructure\File\FileException; -use SP\Infrastructure\File\FileHandler; -use SP\Infrastructure\File\XmlHandler; -use stdClass; - -/** - * Class XmlHandlerTest - * - * Tests unitarios para comprobar el funcionamiento de la clase SP\Infrastructure\File\XmlHandler - * - * @package SPT - */ -class XmlHandlerTest extends TestCase -{ - /** - * @var XmlHandler - */ - protected static $xmlHandler; - /** - * @var object Objeto con los datos a guardar en el archivo XML - */ - protected static $itemsData; - /** - * @var array Elementos del archivo XML - */ - protected $items; - - public static function setUpBeforeClass(): void - { - $file = RESOURCE_PATH . DIRECTORY_SEPARATOR . 'config.xml'; - self::$xmlHandler = new XmlHandler(new FileHandler($file)); - - self::$itemsData = new stdClass(); - self::$itemsData->configString = 'Hello world.'; - self::$itemsData->configNumber = 1; - self::$itemsData->configArray = [1, 2, 3, 4]; - } - - /** - * Test para comprobar el guardado de un archivo XML - * - * @doesNotPerformAssertions - * @throws FileException - */ - public function testSave() - { - self::$xmlHandler->save(self::$itemsData, 'config'); - } - - /** - * Test para comprobar la carga de un archivo XML - * - * @throws FileException - */ - public function testLoadMissingNode() - { - $this->expectException(RuntimeException::class); - - self::$xmlHandler->load('root')->getItems(); - } - - /** - * Test para comprobar la carga de un archivo XML - * - * @throws FileException - */ - public function testLoad() - { - $this->items = self::$xmlHandler->load('config')->getItems(); - - $this->assertTrue(is_array($this->items)); - $this->assertCount(3, $this->items); - - $this->assertSame(self::$itemsData->configString, $this->items['configString']); - $this->assertSame(self::$itemsData->configNumber, $this->items['configNumber']); - - $this->assertTrue(is_array($this->items['configArray'])); - $this->assertCount(count(self::$itemsData->configArray), $this->items['configArray']); - } - - /** - * Test para comprobar el guardado de un archivo XML - * - * @throws FileException - */ - public function testSaveNoItems() - { - $this->expectException(RuntimeException::class); - - self::$xmlHandler->save(null, 'config'); - } -}