From a74725fc2fb8479f282afd312a6de934235ecae6 Mon Sep 17 00:00:00 2001 From: alexmerlin Date: Tue, 4 Jun 2024 17:05:44 +0300 Subject: [PATCH] Refactor: Transfer responsibility from handlers to services. Signed-off-by: alexmerlin --- src/Admin/src/Command/AdminCreateCommand.php | 5 - .../src/Factory/AdminCreateCommandFactory.php | 13 ++- src/Admin/src/Handler/AdminHandler.php | 29 +----- src/Admin/src/Handler/AdminRoleHandler.php | 10 +- src/Admin/src/RoutesDelegator.php | 4 +- src/Admin/src/Service/AdminRoleService.php | 13 ++- .../src/Service/AdminRoleServiceInterface.php | 6 +- src/Admin/src/Service/AdminService.php | 47 ++++----- .../src/Service/AdminServiceInterface.php | 5 +- src/App/src/Entity/OAuthAuthCode.php | 4 +- .../AuthenticationMiddlewareFactory.php | 9 +- .../Factory/ErrorResponseGeneratorFactory.php | 4 + .../OAuthAccessTokenRepositoryFactory.php | 4 +- .../OAuthAuthCodeRepositoryFactory.php | 4 +- .../Factory/OAuthClientRepositoryFactory.php | 4 +- .../OAuthRefreshTokenRepositoryFactory.php | 4 +- .../Factory/OAuthScopeRepositoryFactory.php | 4 +- .../src/Factory/RouteListCommandFactory.php | 9 +- .../Factory/TokenGenerateCommandFactory.php | 9 +- src/App/src/Factory/UserRepositoryFactory.php | 4 +- src/App/src/Handler/HandlerTrait.php | 6 +- src/App/src/Message.php | 7 +- .../Middleware/AuthorizationMiddleware.php | 4 +- src/App/src/RoutesDelegator.php | 4 +- .../src/Handler/AccountActivateHandler.php | 18 +--- src/User/src/Handler/AccountHandler.php | 5 +- .../src/Handler/AccountRecoveryHandler.php | 10 +- .../Handler/AccountResetPasswordHandler.php | 12 +-- src/User/src/Handler/UserActivateHandler.php | 13 +-- src/User/src/Handler/UserAvatarHandler.php | 21 +--- src/User/src/Handler/UserHandler.php | 25 +---- src/User/src/Handler/UserRoleHandler.php | 10 +- src/User/src/RoutesDelegator.php | 4 +- src/User/src/Service/UserAvatarService.php | 11 ++- src/User/src/Service/UserRoleService.php | 14 ++- .../src/Service/UserRoleServiceInterface.php | 6 +- src/User/src/Service/UserService.php | 95 ++++++++++++------- src/User/src/Service/UserServiceInterface.php | 17 +++- 38 files changed, 235 insertions(+), 238 deletions(-) diff --git a/src/Admin/src/Command/AdminCreateCommand.php b/src/Admin/src/Command/AdminCreateCommand.php index 39747dc..777d8df 100644 --- a/src/Admin/src/Command/AdminCreateCommand.php +++ b/src/Admin/src/Command/AdminCreateCommand.php @@ -85,11 +85,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int private function getData(InputInterface $input): array { $role = $this->adminRoleService->findOneBy(['name' => AdminRole::ROLE_ADMIN]); - if (! $role instanceof AdminRole) { - throw new NotFoundException( - sprintf(Message::ADMIN_ROLE_MISSING, AdminRole::ROLE_ADMIN) - ); - } return [ 'identity' => $input->getOption('identity'), diff --git a/src/Admin/src/Factory/AdminCreateCommandFactory.php b/src/Admin/src/Factory/AdminCreateCommandFactory.php index 52adc54..6d174f1 100644 --- a/src/Admin/src/Factory/AdminCreateCommandFactory.php +++ b/src/Admin/src/Factory/AdminCreateCommandFactory.php @@ -11,6 +11,8 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function assert; + class AdminCreateCommandFactory { /** @@ -19,9 +21,12 @@ class AdminCreateCommandFactory */ public function __invoke(ContainerInterface $container): AdminCreateCommand { - return new AdminCreateCommand( - $container->get(AdminService::class), - $container->get(AdminRoleService::class) - ); + $adminService = $container->get(AdminService::class); + assert($adminService instanceof AdminService); + + $adminRoleService = $container->get(AdminRoleService::class); + assert($adminRoleService instanceof AdminRoleService); + + return new AdminCreateCommand($adminService, $adminRoleService); } } diff --git a/src/Admin/src/Handler/AdminHandler.php b/src/Admin/src/Handler/AdminHandler.php index 486fcb2..349613f 100644 --- a/src/Admin/src/Handler/AdminHandler.php +++ b/src/Admin/src/Handler/AdminHandler.php @@ -4,7 +4,6 @@ namespace Api\Admin\Handler; -use Api\Admin\Entity\Admin; use Api\Admin\InputFilter\CreateAdminInputFilter; use Api\Admin\InputFilter\UpdateAdminInputFilter; use Api\Admin\Service\AdminServiceInterface; @@ -12,7 +11,6 @@ use Api\App\Exception\ConflictException; use Api\App\Exception\NotFoundException; use Api\App\Handler\HandlerTrait; -use Api\App\Message; use Dot\AnnotatedServices\Annotation\Inject; use Mezzio\Hal\HalResponseFactory; use Mezzio\Hal\ResourceGenerator; @@ -20,8 +18,6 @@ use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; -use function sprintf; - class AdminHandler implements RequestHandlerInterface { use HandlerTrait; @@ -47,12 +43,7 @@ public function __construct( */ public function delete(ServerRequestInterface $request): ResponseInterface { - $uuid = $request->getAttribute('uuid'); - - $admin = $this->adminService->findOneBy(['uuid' => $uuid]); - if (! $admin instanceof Admin) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'admin', $uuid)); - } + $admin = $this->adminService->findOneBy(['uuid' => $request->getAttribute('uuid')]); $this->adminService->deleteAdmin($admin); @@ -64,12 +55,7 @@ public function delete(ServerRequestInterface $request): ResponseInterface */ public function get(ServerRequestInterface $request): ResponseInterface { - $uuid = $request->getAttribute('uuid'); - - $admin = $this->adminService->findOneBy(['uuid' => $uuid]); - if (! $admin instanceof Admin) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'admin', $uuid)); - } + $admin = $this->adminService->findOneBy(['uuid' => $request->getAttribute('uuid')]); return $this->createResponse($request, $admin); } @@ -91,15 +77,10 @@ public function patch(ServerRequestInterface $request): ResponseInterface throw (new BadRequestException())->setMessages($inputFilter->getMessages()); } - $uuid = $request->getAttribute('uuid'); - $admin = $this->adminService->findOneBy(['uuid' => $uuid]); - if (! $admin instanceof Admin) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'admin', $uuid)); - } - - $user = $this->adminService->updateAdmin($admin, $inputFilter->getValues()); + $admin = $this->adminService->findOneBy(['uuid' => $request->getAttribute('uuid')]); + $this->adminService->updateAdmin($admin, $inputFilter->getValues()); - return $this->createResponse($request, $user); + return $this->createResponse($request, $admin); } /** diff --git a/src/Admin/src/Handler/AdminRoleHandler.php b/src/Admin/src/Handler/AdminRoleHandler.php index 6845c51..9067672 100644 --- a/src/Admin/src/Handler/AdminRoleHandler.php +++ b/src/Admin/src/Handler/AdminRoleHandler.php @@ -4,11 +4,9 @@ namespace Api\Admin\Handler; -use Api\Admin\Entity\AdminRole; use Api\Admin\Service\AdminRoleServiceInterface; use Api\App\Exception\NotFoundException; use Api\App\Handler\HandlerTrait; -use Api\App\Message; use Dot\AnnotatedServices\Annotation\Inject; use Mezzio\Hal\HalResponseFactory; use Mezzio\Hal\ResourceGenerator; @@ -16,8 +14,6 @@ use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; -use function sprintf; - class AdminRoleHandler implements RequestHandlerInterface { use HandlerTrait; @@ -43,11 +39,7 @@ public function __construct( */ public function get(ServerRequestInterface $request): ResponseInterface { - $uuid = $request->getAttribute('uuid'); - $role = $this->roleService->findOneBy(['uuid' => $uuid]); - if (! $role instanceof AdminRole) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'role', $uuid)); - } + $role = $this->roleService->findOneBy(['uuid' => $request->getAttribute('uuid')]); return $this->createResponse($request, $role); } diff --git a/src/Admin/src/RoutesDelegator.php b/src/Admin/src/RoutesDelegator.php index 9250f33..0239f78 100644 --- a/src/Admin/src/RoutesDelegator.php +++ b/src/Admin/src/RoutesDelegator.php @@ -10,12 +10,14 @@ use Mezzio\Application; use Psr\Container\ContainerInterface; +use function assert; + class RoutesDelegator { public function __invoke(ContainerInterface $container, string $serviceName, callable $callback): Application { - /** @var Application $app */ $app = $callback(); + assert($app instanceof Application); $uuid = \Api\App\RoutesDelegator::REGEXP_UUID; diff --git a/src/Admin/src/Service/AdminRoleService.php b/src/Admin/src/Service/AdminRoleService.php index fa73e30..64101ce 100644 --- a/src/Admin/src/Service/AdminRoleService.php +++ b/src/Admin/src/Service/AdminRoleService.php @@ -7,6 +7,8 @@ use Api\Admin\Collection\AdminRoleCollection; use Api\Admin\Entity\AdminRole; use Api\Admin\Repository\AdminRoleRepository; +use Api\App\Exception\NotFoundException; +use Api\App\Message; use Dot\AnnotatedServices\Annotation\Inject; class AdminRoleService implements AdminRoleServiceInterface @@ -21,14 +23,17 @@ public function __construct( ) { } - public function findOneBy(array $params = []): ?AdminRole + /** + * @throws NotFoundException + */ + public function findOneBy(array $params = []): AdminRole { $role = $this->adminRoleRepository->findOneBy($params); - if ($role instanceof AdminRole) { - return $role; + if (! $role instanceof AdminRole) { + throw new NotFoundException(Message::ROLE_NOT_FOUND); } - return null; + return $role; } public function getAdminRoles(array $params = []): AdminRoleCollection diff --git a/src/Admin/src/Service/AdminRoleServiceInterface.php b/src/Admin/src/Service/AdminRoleServiceInterface.php index bc5452d..4a95eed 100644 --- a/src/Admin/src/Service/AdminRoleServiceInterface.php +++ b/src/Admin/src/Service/AdminRoleServiceInterface.php @@ -6,10 +6,14 @@ use Api\Admin\Collection\AdminRoleCollection; use Api\Admin\Entity\AdminRole; +use Api\App\Exception\NotFoundException; interface AdminRoleServiceInterface { - public function findOneBy(array $params = []): ?AdminRole; + /** + * @throws NotFoundException + */ + public function findOneBy(array $params = []): AdminRole; public function getAdminRoles(array $params = []): AdminRoleCollection; } diff --git a/src/Admin/src/Service/AdminService.php b/src/Admin/src/Service/AdminService.php index 0f5e9ad..53d4bac 100644 --- a/src/Admin/src/Service/AdminService.php +++ b/src/Admin/src/Service/AdminService.php @@ -13,8 +13,6 @@ use Api\App\Message; use Dot\AnnotatedServices\Annotation\Inject; -use function sprintf; - class AdminService implements AdminServiceInterface { /** @@ -48,22 +46,14 @@ public function createAdmin(array $data = []): Admin if (! empty($data['roles'])) { foreach ($data['roles'] as $roleData) { - $role = $this->adminRoleService->findOneBy(['uuid' => $roleData['uuid']]); - if (! $role instanceof AdminRole) { - throw new NotFoundException( - sprintf(Message::NOT_FOUND_BY_UUID, 'role', $roleData['uuid']) - ); - } - $admin->addRole($role); - } - } else { - $role = $this->adminRoleService->findOneBy(['name' => AdminRole::ROLE_ADMIN]); - if (! $role instanceof AdminRole) { - throw new NotFoundException( - sprintf(Message::NOT_FOUND_BY_NAME, 'role', AdminRole::ROLE_ADMIN) + $admin->addRole( + $this->adminRoleService->findOneBy(['uuid' => $roleData['uuid']]) ); } - $admin->addRole($role); + } else { + $admin->addRole( + $this->adminRoleService->findOneBy(['name' => AdminRole::ROLE_ADMIN]) + ); } return $this->adminRepository->saveAdmin($admin); @@ -78,17 +68,24 @@ public function deleteAdmin(Admin $admin): void public function exists(string $identity = ''): bool { - return $this->findOneBy(['identity' => $identity]) instanceof Admin; + try { + return $this->findOneBy(['identity' => $identity]) instanceof Admin; + } catch (NotFoundException) { + return false; + } } - public function findOneBy(array $params = []): ?Admin + /** + * @throws NotFoundException + */ + public function findOneBy(array $params = []): Admin { $admin = $this->adminRepository->findOneBy($params); - if ($admin instanceof Admin) { - return $admin; + if (! $admin instanceof Admin) { + throw new NotFoundException(Message::ADMIN_NOT_FOUND); } - return null; + return $admin; } public function getAdmins(array $params = []): AdminCollection @@ -121,11 +118,9 @@ public function updateAdmin(Admin $admin, array $data = []): Admin if (! empty($data['roles'])) { $admin->resetRoles(); foreach ($data['roles'] as $roleData) { - $role = $this->adminRoleService->findOneBy(['uuid' => $roleData['uuid']]); - if (! $role instanceof AdminRole) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'role', $roleData['uuid'])); - } - $admin->addRole($role); + $admin->addRole( + $this->adminRoleService->findOneBy(['uuid' => $roleData['uuid']]) + ); } } diff --git a/src/Admin/src/Service/AdminServiceInterface.php b/src/Admin/src/Service/AdminServiceInterface.php index e4482b7..cea80a3 100644 --- a/src/Admin/src/Service/AdminServiceInterface.php +++ b/src/Admin/src/Service/AdminServiceInterface.php @@ -21,7 +21,10 @@ public function deleteAdmin(Admin $admin): void; public function exists(string $identity = ''): bool; - public function findOneBy(array $params = []): ?Admin; + /** + * @throws NotFoundException + */ + public function findOneBy(array $params = []): Admin; public function getAdmins(array $params = []): AdminCollection; diff --git a/src/App/src/Entity/OAuthAuthCode.php b/src/App/src/Entity/OAuthAuthCode.php index b7749a0..44564d6 100644 --- a/src/App/src/Entity/OAuthAuthCode.php +++ b/src/App/src/Entity/OAuthAuthCode.php @@ -15,6 +15,8 @@ use League\OAuth2\Server\Entities\ScopeEntityInterface; use League\OAuth2\Server\Entities\Traits\AuthCodeTrait; +use function assert; + #[ORM\Entity(repositoryClass: OAuthAuthCodeRepository::class)] #[ORM\Table(name: "oauth_auth_codes")] class OAuthAuthCode implements AuthCodeEntityInterface @@ -97,8 +99,8 @@ public function setUserIdentifier($identifier): self public function getUserIdentifier(): ?string { - /** @var OAuthClient $client */ $client = $this->getClient(); + assert($client instanceof OAuthClient); if (null === $user = $client->getUser()) { return null; diff --git a/src/App/src/Factory/AuthenticationMiddlewareFactory.php b/src/App/src/Factory/AuthenticationMiddlewareFactory.php index fcb0f94..dbb26c3 100644 --- a/src/App/src/Factory/AuthenticationMiddlewareFactory.php +++ b/src/App/src/Factory/AuthenticationMiddlewareFactory.php @@ -11,6 +11,8 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function assert; + class AuthenticationMiddlewareFactory { /** @@ -23,8 +25,9 @@ public function __invoke(ContainerInterface $container): AuthenticationMiddlewar throw new InvalidConfigException('AuthenticationInterface service is missing'); } - return new AuthenticationMiddleware( - $container->get(AuthenticationInterface::class) - ); + $authentication = $container->get(AuthenticationInterface::class); + assert($authentication instanceof AuthenticationInterface); + + return new AuthenticationMiddleware($authentication); } } diff --git a/src/App/src/Factory/ErrorResponseGeneratorFactory.php b/src/App/src/Factory/ErrorResponseGeneratorFactory.php index ebeda28..65151ad 100644 --- a/src/App/src/Factory/ErrorResponseGeneratorFactory.php +++ b/src/App/src/Factory/ErrorResponseGeneratorFactory.php @@ -9,6 +9,9 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function assert; +use function is_array; + class ErrorResponseGeneratorFactory { /** @@ -18,6 +21,7 @@ class ErrorResponseGeneratorFactory public function __invoke(ContainerInterface $container): ErrorResponseGenerator { $config = $container->has('config') ? $container->get('config') : []; + assert(is_array($config)); return new ErrorResponseGenerator($config['debug'] ?? false); } diff --git a/src/App/src/Factory/OAuthAccessTokenRepositoryFactory.php b/src/App/src/Factory/OAuthAccessTokenRepositoryFactory.php index d279aff..0f186d3 100644 --- a/src/App/src/Factory/OAuthAccessTokenRepositoryFactory.php +++ b/src/App/src/Factory/OAuthAccessTokenRepositoryFactory.php @@ -11,6 +11,8 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function assert; + class OAuthAccessTokenRepositoryFactory { /** @@ -19,8 +21,8 @@ class OAuthAccessTokenRepositoryFactory */ public function __invoke(ContainerInterface $container): ObjectRepository { - /** @var EntityManagerInterface $entityManager */ $entityManager = $container->get(EntityManagerInterface::class); + assert($entityManager instanceof EntityManagerInterface); return $entityManager->getRepository(OAuthAccessToken::class); } diff --git a/src/App/src/Factory/OAuthAuthCodeRepositoryFactory.php b/src/App/src/Factory/OAuthAuthCodeRepositoryFactory.php index ca78dec..f42e054 100644 --- a/src/App/src/Factory/OAuthAuthCodeRepositoryFactory.php +++ b/src/App/src/Factory/OAuthAuthCodeRepositoryFactory.php @@ -11,6 +11,8 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function assert; + class OAuthAuthCodeRepositoryFactory { /** @@ -19,8 +21,8 @@ class OAuthAuthCodeRepositoryFactory */ public function __invoke(ContainerInterface $container): ObjectRepository { - /** @var EntityManagerInterface $entityManager */ $entityManager = $container->get(EntityManagerInterface::class); + assert($entityManager instanceof EntityManagerInterface); return $entityManager->getRepository(OAuthAuthCode::class); } diff --git a/src/App/src/Factory/OAuthClientRepositoryFactory.php b/src/App/src/Factory/OAuthClientRepositoryFactory.php index 558eb4a..6e92917 100644 --- a/src/App/src/Factory/OAuthClientRepositoryFactory.php +++ b/src/App/src/Factory/OAuthClientRepositoryFactory.php @@ -11,6 +11,8 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function assert; + class OAuthClientRepositoryFactory { /** @@ -19,8 +21,8 @@ class OAuthClientRepositoryFactory */ public function __invoke(ContainerInterface $container): ObjectRepository { - /** @var EntityManagerInterface $entityManager */ $entityManager = $container->get(EntityManagerInterface::class); + assert($entityManager instanceof EntityManagerInterface); return $entityManager->getRepository(OAuthClient::class); } diff --git a/src/App/src/Factory/OAuthRefreshTokenRepositoryFactory.php b/src/App/src/Factory/OAuthRefreshTokenRepositoryFactory.php index 885bb43..9d4c2cf 100644 --- a/src/App/src/Factory/OAuthRefreshTokenRepositoryFactory.php +++ b/src/App/src/Factory/OAuthRefreshTokenRepositoryFactory.php @@ -11,6 +11,8 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function assert; + class OAuthRefreshTokenRepositoryFactory { /** @@ -19,8 +21,8 @@ class OAuthRefreshTokenRepositoryFactory */ public function __invoke(ContainerInterface $container): ObjectRepository { - /** @var EntityManagerInterface $entityManager */ $entityManager = $container->get(EntityManagerInterface::class); + assert($entityManager instanceof EntityManagerInterface); return $entityManager->getRepository(OAuthRefreshToken::class); } diff --git a/src/App/src/Factory/OAuthScopeRepositoryFactory.php b/src/App/src/Factory/OAuthScopeRepositoryFactory.php index 48f0e11..04e377d 100644 --- a/src/App/src/Factory/OAuthScopeRepositoryFactory.php +++ b/src/App/src/Factory/OAuthScopeRepositoryFactory.php @@ -11,6 +11,8 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function assert; + class OAuthScopeRepositoryFactory { /** @@ -19,8 +21,8 @@ class OAuthScopeRepositoryFactory */ public function __invoke(ContainerInterface $container): ObjectRepository { - /** @var EntityManagerInterface $entityManager */ $entityManager = $container->get(EntityManagerInterface::class); + assert($entityManager instanceof EntityManagerInterface); return $entityManager->getRepository(OAuthScope::class); } diff --git a/src/App/src/Factory/RouteListCommandFactory.php b/src/App/src/Factory/RouteListCommandFactory.php index 2fa7a95..bb8c454 100644 --- a/src/App/src/Factory/RouteListCommandFactory.php +++ b/src/App/src/Factory/RouteListCommandFactory.php @@ -10,6 +10,8 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function assert; + class RouteListCommandFactory { /** @@ -18,8 +20,9 @@ class RouteListCommandFactory */ public function __invoke(ContainerInterface $container): RouteListCommand { - return new RouteListCommand( - $container->get(Application::class) - ); + $application = $container->get(Application::class); + assert($application instanceof Application); + + return new RouteListCommand($application); } } diff --git a/src/App/src/Factory/TokenGenerateCommandFactory.php b/src/App/src/Factory/TokenGenerateCommandFactory.php index 9e0d941..a1dc867 100644 --- a/src/App/src/Factory/TokenGenerateCommandFactory.php +++ b/src/App/src/Factory/TokenGenerateCommandFactory.php @@ -10,6 +10,8 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function assert; + class TokenGenerateCommandFactory { /** @@ -18,8 +20,9 @@ class TokenGenerateCommandFactory */ public function __invoke(ContainerInterface $container): TokenGenerateCommand { - return new TokenGenerateCommand( - $container->get(ErrorReportServiceInterface::class) - ); + $errorReportService = $container->get(ErrorReportServiceInterface::class); + assert($errorReportService instanceof ErrorReportServiceInterface); + + return new TokenGenerateCommand($errorReportService); } } diff --git a/src/App/src/Factory/UserRepositoryFactory.php b/src/App/src/Factory/UserRepositoryFactory.php index 62cfa50..c360943 100644 --- a/src/App/src/Factory/UserRepositoryFactory.php +++ b/src/App/src/Factory/UserRepositoryFactory.php @@ -11,6 +11,8 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function assert; + class UserRepositoryFactory { /** @@ -19,8 +21,8 @@ class UserRepositoryFactory */ public function __invoke(ContainerInterface $container): ObjectRepository { - /** @var EntityManagerInterface $entityManager */ $entityManager = $container->get(EntityManagerInterface::class); + assert($entityManager instanceof EntityManagerInterface); return $entityManager->getRepository(User::class); } diff --git a/src/App/src/Handler/HandlerTrait.php b/src/App/src/Handler/HandlerTrait.php index e0fcc28..08c1ae3 100644 --- a/src/App/src/Handler/HandlerTrait.php +++ b/src/App/src/Handler/HandlerTrait.php @@ -24,6 +24,7 @@ use RuntimeException; use function array_key_exists; +use function assert; use function is_array; use function method_exists; use function sprintf; @@ -85,9 +86,10 @@ private function isGetCollectionRequest(ServerRequestInterface $request, array $ ); } - /** @var RouteResult $routeResult */ $routeResult = $request->getAttribute(RouteResult::class); - $routeName = $routeResult->getMatchedRouteName(); + assert($routeResult instanceof RouteResult); + + $routeName = $routeResult->getMatchedRouteName(); $halConfig = null; foreach ($config[MetadataMap::class] as $cfg) { diff --git a/src/App/src/Message.php b/src/App/src/Message.php index 92eab7b..95d25ec 100644 --- a/src/App/src/Message.php +++ b/src/App/src/Message.php @@ -8,14 +8,13 @@ class Message { public const ADMIN_CREATED = 'Admin account has been created.'; public const ADMIN_NOT_ACTIVATED = 'This account is deactivated.'; - public const ADMIN_ROLE_MISSING = 'Admin role \'%s\' is missing.'; + public const ADMIN_NOT_FOUND = 'Admin not found.'; public const AVATAR_MISSING = 'This user account has no avatar associated with it.'; public const DUPLICATE_EMAIL = 'An account with this email address already exists.'; public const DUPLICATE_IDENTITY = 'An account with this identity already exists.'; public const ERROR_REPORT_OK = 'Error report successfully saved.'; public const ERROR_REPORT_NOT_ALLOWED = 'You are not allowed to report errors.'; public const ERROR_REPORT_NOT_ENABLED = 'Remote error reporting is not enabled.'; - public const INVALID_ACTIVATION_CODE = 'Invalid activation code.'; public const INVALID_CLIENT_ID = 'Invalid client_id.'; public const INVALID_CONFIG = 'Invalid configuration value: \'%s\''; public const INVALID_VALUE = 'The value specified for \'%s\' is invalid.'; @@ -26,8 +25,6 @@ class Message public const MAIL_SENT_USER_ACTIVATION = 'User activation mail has been successfully sent to \'%s\''; public const MAIL_NOT_SENT_TO = 'Could not send mail to \'%s\'.'; public const MISSING_CONFIG = 'Missing configuration value: \'%s\'.'; - public const NOT_FOUND_BY_NAME = 'Unable to find %s identified by name: %s'; - public const NOT_FOUND_BY_UUID = 'Unable to find %s identified by UUID: %s'; public const RESET_PASSWORD_EXPIRED = 'Password reset request for hash: \'%s\' is invalid (expired).'; public const RESET_PASSWORD_NOT_FOUND = 'Could not find password reset request identified by hash: \'%s\''; public const RESET_PASSWORD_OK = 'Password successfully modified.'; @@ -36,11 +33,11 @@ class Message public const RESOURCE_NOT_ALLOWED = 'You are not allowed to access this resource.'; public const RESTRICTION_IMAGE = 'File must be an image (jpg, png).'; public const RESTRICTION_ROLES = 'User accounts must have at least one role.'; + public const ROLE_NOT_FOUND = 'Role not found.'; public const USER_ACTIVATED = 'This account has been activated.'; public const USER_ALREADY_ACTIVATED = 'This account is already active.'; public const USER_NOT_ACTIVATED = 'User account must be activated first.'; public const USER_NOT_FOUND = 'User not found.'; - public const USER_NOT_FOUND_BY_EMAIL = 'Could not find account identified by email \'%s\''; public const USER_NOT_FOUND_BY_IDENTITY = 'Could not find account by identity \'%s\''; public const VALIDATOR_MIN_LENGTH = '%s must be at least %d characters long.'; public const VALIDATOR_PASSWORD_MISMATCH = 'Password confirmation does not match the provided password.'; diff --git a/src/App/src/Middleware/AuthorizationMiddleware.php b/src/App/src/Middleware/AuthorizationMiddleware.php index d7a75dd..5d840c0 100644 --- a/src/App/src/Middleware/AuthorizationMiddleware.php +++ b/src/App/src/Middleware/AuthorizationMiddleware.php @@ -22,6 +22,7 @@ use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; +use function assert; use function sprintf; class AuthorizationMiddleware implements MiddlewareInterface @@ -42,8 +43,9 @@ public function __construct( public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { - /** @var UserIdentity $defaultUser */ $defaultUser = $request->getAttribute(UserInterface::class); + assert($defaultUser instanceof UserIdentity); + switch ($defaultUser->getDetail('oauth_client_id')) { case 'admin': $user = $this->adminRepository->findOneBy(['identity' => $defaultUser->getIdentity()]); diff --git a/src/App/src/RoutesDelegator.php b/src/App/src/RoutesDelegator.php index 72240c9..61f7a0a 100644 --- a/src/App/src/RoutesDelegator.php +++ b/src/App/src/RoutesDelegator.php @@ -11,14 +11,16 @@ use Mezzio\Authentication\OAuth2\TokenEndpointHandler; use Psr\Container\ContainerInterface; +use function assert; + class RoutesDelegator { public const REGEXP_UUID = '{uuid:[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}}'; public function __invoke(ContainerInterface $container, string $serviceName, callable $callback): Application { - /** @var Application $app */ $app = $callback(); + assert($app instanceof Application); /** * Home page diff --git a/src/User/src/Handler/AccountActivateHandler.php b/src/User/src/Handler/AccountActivateHandler.php index 0537c37..099329c 100644 --- a/src/User/src/Handler/AccountActivateHandler.php +++ b/src/User/src/Handler/AccountActivateHandler.php @@ -9,7 +9,6 @@ use Api\App\Exception\NotFoundException; use Api\App\Handler\HandlerTrait; use Api\App\Message; -use Api\User\Entity\User; use Api\User\InputFilter\ActivateAccountInputFilter; use Api\User\Service\UserServiceInterface; use Dot\AnnotatedServices\Annotation\Inject; @@ -49,13 +48,7 @@ public function __construct( */ public function patch(ServerRequestInterface $request): ResponseInterface { - $hash = $request->getAttribute('hash'); - - $user = $this->userService->findOneBy(['hash' => $hash]); - if (! $user instanceof User) { - throw new NotFoundException(Message::INVALID_ACTIVATION_CODE); - } - + $user = $this->userService->findOneBy(['hash' => $request->getAttribute('hash')]); if ($user->isActive()) { throw new ConflictException(Message::USER_ALREADY_ACTIVATED); } @@ -78,17 +71,12 @@ public function post(ServerRequestInterface $request): ResponseInterface throw (new BadRequestException())->setMessages($inputFilter->getMessages()); } - $email = $inputFilter->getValue('email'); - $user = $this->userService->findByEmail($email); - if (! $user instanceof User) { - throw new NotFoundException(sprintf(Message::USER_NOT_FOUND_BY_EMAIL, $email)); - } - + $user = $this->userService->findByEmail($inputFilter->getValue('email')); if ($user->isActive()) { throw new ConflictException(Message::USER_ALREADY_ACTIVATED); } - $user = $this->userService->activateUser($user); + $this->userService->activateUser($user); $this->userService->sendActivationMail($user); return $this->infoResponse( diff --git a/src/User/src/Handler/AccountHandler.php b/src/User/src/Handler/AccountHandler.php index 05e8f78..5b0e358 100644 --- a/src/User/src/Handler/AccountHandler.php +++ b/src/User/src/Handler/AccountHandler.php @@ -6,6 +6,7 @@ use Api\App\Exception\BadRequestException; use Api\App\Exception\ConflictException; +use Api\App\Exception\NotFoundException; use Api\App\Handler\HandlerTrait; use Api\User\Entity\User; use Api\User\InputFilter\CreateUserInputFilter; @@ -29,7 +30,7 @@ class AccountHandler implements RequestHandlerInterface * HalResponseFactory::class, * ResourceGenerator::class, * UserServiceInterface::class, - * "config" + * "config", * }) */ public function __construct( @@ -78,6 +79,7 @@ public function patch(ServerRequestInterface $request): ResponseInterface * @throws BadRequestException * @throws ConflictException * @throws MailException + * @throws NotFoundException */ public function post(ServerRequestInterface $request): ResponseInterface { @@ -89,7 +91,6 @@ public function post(ServerRequestInterface $request): ResponseInterface } $user = $this->userService->createUser($inputFilter->getValues()); - $this->userService->sendActivationMail($user); return $this->createdResponse($request, $user); diff --git a/src/User/src/Handler/AccountRecoveryHandler.php b/src/User/src/Handler/AccountRecoveryHandler.php index c3ba86d..5227917 100644 --- a/src/User/src/Handler/AccountRecoveryHandler.php +++ b/src/User/src/Handler/AccountRecoveryHandler.php @@ -8,7 +8,6 @@ use Api\App\Exception\NotFoundException; use Api\App\Handler\HandlerTrait; use Api\App\Message; -use Api\User\Entity\User; use Api\User\InputFilter\RecoverIdentityInputFilter; use Api\User\Service\UserServiceInterface; use Dot\AnnotatedServices\Annotation\Inject; @@ -19,8 +18,6 @@ use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; -use function sprintf; - class AccountRecoveryHandler implements RequestHandlerInterface { use HandlerTrait; @@ -53,12 +50,7 @@ public function post(ServerRequestInterface $request): ResponseInterface throw (new BadRequestException())->setMessages($inputFilter->getMessages()); } - $email = $inputFilter->getValue('email'); - $user = $this->userService->findByEmail($email); - if (! $user instanceof User) { - throw new NotFoundException(sprintf(Message::USER_NOT_FOUND_BY_EMAIL, $email)); - } - + $user = $this->userService->findByEmail($inputFilter->getValue('email')); $this->userService->sendRecoverIdentityMail($user); return $this->infoResponse(Message::MAIL_SENT_RECOVER_IDENTITY); diff --git a/src/User/src/Handler/AccountResetPasswordHandler.php b/src/User/src/Handler/AccountResetPasswordHandler.php index 0df19b4..97ab3af 100644 --- a/src/User/src/Handler/AccountResetPasswordHandler.php +++ b/src/User/src/Handler/AccountResetPasswordHandler.php @@ -11,7 +11,6 @@ use Api\App\Handler\HandlerTrait; use Api\App\Message; use Api\User\Entity\User; -use Api\User\Entity\UserResetPasswordEntity; use Api\User\InputFilter\ResetPasswordInputFilter; use Api\User\InputFilter\UpdatePasswordInputFilter; use Api\User\Service\UserServiceInterface; @@ -54,10 +53,6 @@ public function get(ServerRequestInterface $request): ResponseInterface $hash = $request->getAttribute('hash'); $userResetPassword = $this->userService->findResetPasswordByHash($hash); - if (! $userResetPassword instanceof UserResetPasswordEntity) { - throw new NotFoundException(sprintf(Message::RESET_PASSWORD_NOT_FOUND, $hash)); - } - if (! $userResetPassword->isValid()) { throw new ExpiredException(sprintf(Message::RESET_PASSWORD_EXPIRED, $hash)); } @@ -80,10 +75,6 @@ public function patch(ServerRequestInterface $request): ResponseInterface $hash = $request->getAttribute('hash'); $userResetPassword = $this->userService->findResetPasswordByHash($hash); - if (! $userResetPassword instanceof UserResetPasswordEntity) { - throw new NotFoundException(sprintf(Message::RESET_PASSWORD_NOT_FOUND, $hash)); - } - if (! $userResetPassword->isValid()) { throw new ExpiredException(sprintf(Message::RESET_PASSWORD_EXPIRED, $hash)); } @@ -131,8 +122,7 @@ public function post(ServerRequestInterface $request): ResponseInterface throw new NotFoundException(Message::USER_NOT_FOUND); } - $user = $this->userService->updateUser($user->createResetPassword()); - + $this->userService->updateUser($user->createResetPassword()); $this->userService->sendResetPasswordRequestedMail($user); return $this->infoResponse(Message::MAIL_SENT_RESET_PASSWORD); diff --git a/src/User/src/Handler/UserActivateHandler.php b/src/User/src/Handler/UserActivateHandler.php index a3fd39d..f86ffa6 100644 --- a/src/User/src/Handler/UserActivateHandler.php +++ b/src/User/src/Handler/UserActivateHandler.php @@ -8,7 +8,6 @@ use Api\App\Exception\NotFoundException; use Api\App\Handler\HandlerTrait; use Api\App\Message; -use Api\User\Entity\User; use Api\User\Service\UserServiceInterface; use Dot\AnnotatedServices\Annotation\Inject; use Dot\Mail\Exception\MailException; @@ -18,8 +17,6 @@ use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; -use function sprintf; - class UserActivateHandler implements RequestHandlerInterface { use HandlerTrait; @@ -47,18 +44,12 @@ public function __construct( */ public function post(ServerRequestInterface $request): ResponseInterface { - $uuid = $request->getAttribute('uuid'); - $user = $this->userService->findOneBy(['uuid' => $uuid]); - if (! $user instanceof User) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'user', $uuid)); - } - + $user = $this->userService->findOneBy(['uuid' => $request->getAttribute('uuid')]); if ($user->isActive()) { throw new ConflictException(Message::USER_ALREADY_ACTIVATED); } - $user = $this->userService->activateUser($user); - + $this->userService->activateUser($user); $this->userService->sendActivationMail($user); return $this->infoResponse(Message::USER_ACTIVATED); diff --git a/src/User/src/Handler/UserAvatarHandler.php b/src/User/src/Handler/UserAvatarHandler.php index cba8d01..bc2e272 100644 --- a/src/User/src/Handler/UserAvatarHandler.php +++ b/src/User/src/Handler/UserAvatarHandler.php @@ -8,7 +8,6 @@ use Api\App\Exception\NotFoundException; use Api\App\Handler\HandlerTrait; use Api\App\Message; -use Api\User\Entity\User; use Api\User\InputFilter\UpdateAvatarInputFilter; use Api\User\Service\UserAvatarServiceInterface; use Api\User\Service\UserServiceInterface; @@ -19,8 +18,6 @@ use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; -use function sprintf; - class UserAvatarHandler implements RequestHandlerInterface { use HandlerTrait; @@ -48,11 +45,7 @@ public function __construct( */ public function delete(ServerRequestInterface $request): ResponseInterface { - $uuid = $request->getAttribute('uuid'); - $user = $this->userService->findOneBy(['uuid' => $uuid]); - if (! $user instanceof User) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'user', $uuid)); - } + $user = $this->userService->findOneBy(['uuid' => $request->getAttribute('uuid')]); if (! $user->hasAvatar()) { throw new NotFoundException(Message::AVATAR_MISSING); } @@ -67,11 +60,7 @@ public function delete(ServerRequestInterface $request): ResponseInterface */ public function get(ServerRequestInterface $request): ResponseInterface { - $uuid = $request->getAttribute('uuid'); - $user = $this->userService->findOneBy(['uuid' => $uuid]); - if (! $user instanceof User) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'user', $uuid)); - } + $user = $this->userService->findOneBy(['uuid' => $request->getAttribute('uuid')]); if (! $user->hasAvatar()) { throw new NotFoundException(Message::AVATAR_MISSING); } @@ -90,11 +79,7 @@ public function post(ServerRequestInterface $request): ResponseInterface throw (new BadRequestException())->setMessages($inputFilter->getMessages()); } - $uuid = $request->getAttribute('uuid'); - $user = $this->userService->findOneBy(['uuid' => $uuid]); - if (! $user instanceof User) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'user', $uuid)); - } + $user = $this->userService->findOneBy(['uuid' => $request->getAttribute('uuid')]); $userAvatar = $this->userAvatarService->createAvatar($user, $inputFilter->getValue('avatar')); diff --git a/src/User/src/Handler/UserHandler.php b/src/User/src/Handler/UserHandler.php index 1ae8d60..5937da5 100644 --- a/src/User/src/Handler/UserHandler.php +++ b/src/User/src/Handler/UserHandler.php @@ -8,8 +8,6 @@ use Api\App\Exception\ConflictException; use Api\App\Exception\NotFoundException; use Api\App\Handler\HandlerTrait; -use Api\App\Message; -use Api\User\Entity\User; use Api\User\InputFilter\CreateUserInputFilter; use Api\User\InputFilter\UpdateUserInputFilter; use Api\User\Service\UserServiceInterface; @@ -22,8 +20,6 @@ use Psr\Http\Server\RequestHandlerInterface; use RuntimeException; -use function sprintf; - class UserHandler implements RequestHandlerInterface { use HandlerTrait; @@ -50,11 +46,7 @@ public function __construct( */ public function delete(ServerRequestInterface $request): ResponseInterface { - $uuid = $request->getAttribute('uuid'); - $user = $this->userService->findOneBy(['uuid' => $uuid]); - if (! $user instanceof User) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'user', $uuid)); - } + $user = $this->userService->findOneBy(['uuid' => $request->getAttribute('uuid')]); $this->userService->deleteUser($user); @@ -66,11 +58,7 @@ public function delete(ServerRequestInterface $request): ResponseInterface */ public function get(ServerRequestInterface $request): ResponseInterface { - $uuid = $request->getAttribute('uuid'); - $user = $this->userService->findOneBy(['uuid' => $uuid]); - if (! $user instanceof User) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'user', $uuid)); - } + $user = $this->userService->findOneBy(['uuid' => $request->getAttribute('uuid')]); return $this->createResponse($request, $user); } @@ -93,13 +81,8 @@ public function patch(ServerRequestInterface $request): ResponseInterface throw (new BadRequestException())->setMessages($inputFilter->getMessages()); } - $uuid = $request->getAttribute('uuid'); - $user = $this->userService->findOneBy(['uuid' => $uuid]); - if (! $user instanceof User) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'user', $uuid)); - } - - $user = $this->userService->updateUser($user, $inputFilter->getValues()); + $user = $this->userService->findOneBy(['uuid' => $request->getAttribute('uuid')]); + $this->userService->updateUser($user, $inputFilter->getValues()); return $this->createResponse($request, $user); } diff --git a/src/User/src/Handler/UserRoleHandler.php b/src/User/src/Handler/UserRoleHandler.php index 39e2e2f..cb6effc 100644 --- a/src/User/src/Handler/UserRoleHandler.php +++ b/src/User/src/Handler/UserRoleHandler.php @@ -6,8 +6,6 @@ use Api\App\Exception\NotFoundException; use Api\App\Handler\HandlerTrait; -use Api\App\Message; -use Api\User\Entity\UserRole; use Api\User\Service\UserRoleServiceInterface; use Dot\AnnotatedServices\Annotation\Inject; use Mezzio\Hal\HalResponseFactory; @@ -16,8 +14,6 @@ use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; -use function sprintf; - class UserRoleHandler implements RequestHandlerInterface { use HandlerTrait; @@ -43,11 +39,7 @@ public function __construct( */ public function get(ServerRequestInterface $request): ResponseInterface { - $uuid = $request->getAttribute('uuid'); - $role = $this->roleService->findOneBy(['uuid' => $uuid]); - if (! $role instanceof UserRole) { - throw new NotFoundException(sprintf(Message::NOT_FOUND_BY_UUID, 'role', $uuid)); - } + $role = $this->roleService->findOneBy(['uuid' => $request->getAttribute('uuid')]); return $this->createResponse($request, $role); } diff --git a/src/User/src/RoutesDelegator.php b/src/User/src/RoutesDelegator.php index 0ef4c41..3a4af0c 100644 --- a/src/User/src/RoutesDelegator.php +++ b/src/User/src/RoutesDelegator.php @@ -16,12 +16,14 @@ use Mezzio\Application; use Psr\Container\ContainerInterface; +use function assert; + class RoutesDelegator { public function __invoke(ContainerInterface $container, string $serviceName, callable $callback): Application { - /** @var Application $app */ $app = $callback(); + assert($app instanceof Application); $uuid = \Api\App\RoutesDelegator::REGEXP_UUID; diff --git a/src/User/src/Service/UserAvatarService.php b/src/User/src/Service/UserAvatarService.php index 074df9b..c177ce1 100644 --- a/src/User/src/Service/UserAvatarService.php +++ b/src/User/src/Service/UserAvatarService.php @@ -12,6 +12,7 @@ use Psr\Http\Message\UploadedFileInterface; use Ramsey\Uuid\Uuid; +use function assert; use function file_exists; use function is_readable; use function mkdir; @@ -47,12 +48,13 @@ public function createAvatar(User $user, UploadedFile $uploadedFile): UserAvatar if ($user->hasAvatar()) { $avatar = $user->getAvatar(); + assert($avatar instanceof UserAvatar); $this->deleteAvatarFile($path . $avatar->getName()); } else { $avatar = (new UserAvatar())->setUser($user); } - $fileName = $this->createFileName($uploadedFile->getClientMediaType()); + $fileName = $this->createFileName((string) $uploadedFile->getClientMediaType()); $this->saveAvatarImage($uploadedFile, $path . $fileName); $this->userAvatarRepository->saveAvatar($avatar->setName($fileName)); @@ -65,9 +67,12 @@ public function removeAvatar(User $user): void return; } + $avatar = $user->getAvatar(); + assert($avatar instanceof UserAvatar); + $path = $this->getUserAvatarDirectoryPath($user); - $this->userAvatarRepository->deleteAvatar($user->getAvatar()); - $this->deleteAvatarFile($path . $user->getAvatar()->getName()); + $this->userAvatarRepository->deleteAvatar($avatar); + $this->deleteAvatarFile($path . $avatar->getName()); } protected function getUserAvatarDirectoryPath(User $user): string diff --git a/src/User/src/Service/UserRoleService.php b/src/User/src/Service/UserRoleService.php index d4c01c3..03bf223 100644 --- a/src/User/src/Service/UserRoleService.php +++ b/src/User/src/Service/UserRoleService.php @@ -4,6 +4,8 @@ namespace Api\User\Service; +use Api\App\Exception\NotFoundException; +use Api\App\Message; use Api\User\Collection\UserRoleCollection; use Api\User\Entity\UserRole; use Api\User\Repository\UserRoleRepository; @@ -21,9 +23,17 @@ public function __construct( ) { } - public function findOneBy(array $params = []): ?UserRole + /** + * @throws NotFoundException + */ + public function findOneBy(array $params = []): UserRole { - return $this->roleRepository->findOneBy($params); + $role = $this->roleRepository->findOneBy($params); + if (! $role instanceof UserRole) { + throw new NotFoundException(Message::ROLE_NOT_FOUND); + } + + return $role; } public function getRoles(array $params = []): UserRoleCollection diff --git a/src/User/src/Service/UserRoleServiceInterface.php b/src/User/src/Service/UserRoleServiceInterface.php index 3da93aa..0927d81 100644 --- a/src/User/src/Service/UserRoleServiceInterface.php +++ b/src/User/src/Service/UserRoleServiceInterface.php @@ -4,12 +4,16 @@ namespace Api\User\Service; +use Api\App\Exception\NotFoundException; use Api\User\Collection\UserRoleCollection; use Api\User\Entity\UserRole; interface UserRoleServiceInterface { - public function findOneBy(array $params = []): ?UserRole; + /** + * @throws NotFoundException + */ + public function findOneBy(array $params = []): UserRole; public function getRoles(array $params = []): UserRoleCollection; } diff --git a/src/User/src/Service/UserService.php b/src/User/src/Service/UserService.php index acf3f91..e54375b 100644 --- a/src/User/src/Service/UserService.php +++ b/src/User/src/Service/UserService.php @@ -5,6 +5,7 @@ namespace Api\User\Service; use Api\App\Exception\ConflictException; +use Api\App\Exception\NotFoundException; use Api\App\Message; use Api\App\Repository\OAuthAccessTokenRepository; use Api\App\Repository\OAuthRefreshTokenRepository; @@ -66,6 +67,7 @@ public function activateUser(User $user): User /** * @throws ConflictException + * @throws NotFoundException * @throws RuntimeException */ public function createUser(array $data = []): User @@ -92,16 +94,14 @@ public function createUser(array $data = []): User if (! empty($data['roles'])) { foreach ($data['roles'] as $roleData) { - $role = $this->userRoleService->findOneBy(['uuid' => $roleData['uuid']]); - if ($role instanceof UserRole) { - $user->addRole($role); - } + $user->addRole( + $this->userRoleService->findOneBy(['uuid' => $roleData['uuid']]) + ); } } else { - $role = $this->userRoleService->findOneBy(['name' => UserRole::ROLE_USER]); - if ($role instanceof UserRole) { - $user->addRole($role); - } + $user->addRole( + $this->userRoleService->findOneBy(['name' => UserRole::ROLE_USER]) + ); } return $this->userRepository->saveUser($user); @@ -145,62 +145,93 @@ public function anonymizeUser(User $user): User public function exists(string $identity = ''): bool { - return $this->findOneBy(['identity' => $identity]) instanceof User; + try { + $this->findOneBy(['identity' => $identity]); + + return true; + } catch (NotFoundException) { + return false; + } } public function existsOther(string $identity = '', string $uuid = ''): bool { - $user = $this->findOneBy(['identity' => $identity]); - if (! $user instanceof User) { + try { + $user = $this->findOneBy(['identity' => $identity]); + + return $user->getUuid()->toString() !== $uuid; + } catch (NotFoundException) { return false; } - - return $user->getUuid()->toString() !== $uuid; } public function emailExists(string $email = ''): bool { - return $this->findByEmail($email) instanceof User; + try { + $this->findByEmail($email); + + return true; + } catch (NotFoundException) { + return false; + } } public function emailExistsOther(string $email = '', string $uuid = ''): bool { - $user = $this->findByEmail($email); - if (! $user instanceof User) { + try { + $user = $this->findByEmail($email); + + return $user->getUuid()->toString() !== $uuid; + } catch (NotFoundException) { return false; } - - return $user->getUuid()->toString() !== $uuid; } - public function findResetPasswordByHash(?string $hash): ?UserResetPasswordEntity + /** + * @throws NotFoundException + */ + public function findResetPasswordByHash(?string $hash): UserResetPasswordEntity { $userResetPassword = $this->userResetPasswordRepository->findOneBy(['hash' => $hash]); - if ($userResetPassword instanceof UserResetPasswordEntity) { - return $userResetPassword; + if (! $userResetPassword instanceof UserResetPasswordEntity) { + throw new NotFoundException(sprintf(Message::RESET_PASSWORD_NOT_FOUND, (string) $hash)); } - return null; + return $userResetPassword; } - public function findByEmail(string $email): ?User + /** + * @throws NotFoundException + */ + public function findByEmail(string $email): User { - return $this->userDetailRepository->findOneBy(['email' => $email])?->getUser(); + $user = $this->userDetailRepository->findOneBy(['email' => $email])?->getUser(); + if (! $user instanceof User) { + throw new NotFoundException(Message::USER_NOT_FOUND); + } + + return $user; } + /** + * @throws NotFoundException + */ public function findByIdentity(string $identity): ?User { return $this->findOneBy(['identity' => $identity]); } - public function findOneBy(array $params = []): ?User + /** + * @throws NotFoundException + */ + public function findOneBy(array $params = []): User { $user = $this->userRepository->findOneBy($params); - if ($user instanceof User) { - return $user; + if (! $user instanceof User) { + throw new NotFoundException(Message::USER_NOT_FOUND); } - return null; + return $user; } public function getUsers(array $params = []): UserCollection @@ -306,6 +337,7 @@ public function sendWelcomeMail(User $user): bool /** * @throws ConflictException + * @throws NotFoundException * @throws RuntimeException */ public function updateUser(User $user, array $data = []): User @@ -355,10 +387,9 @@ public function updateUser(User $user, array $data = []): User if (! empty($data['roles'])) { $user->resetRoles(); foreach ($data['roles'] as $roleData) { - $role = $this->userRoleService->findOneBy(['uuid' => $roleData['uuid']]); - if ($role instanceof UserRole) { - $user->addRole($role); - } + $user->addRole( + $this->userRoleService->findOneBy(['uuid' => $roleData['uuid']]) + ); } } diff --git a/src/User/src/Service/UserServiceInterface.php b/src/User/src/Service/UserServiceInterface.php index dd8140e..7f6244e 100644 --- a/src/User/src/Service/UserServiceInterface.php +++ b/src/User/src/Service/UserServiceInterface.php @@ -5,6 +5,7 @@ namespace Api\User\Service; use Api\App\Exception\ConflictException; +use Api\App\Exception\NotFoundException; use Api\User\Collection\UserCollection; use Api\User\Entity\User; use Api\User\Entity\UserResetPasswordEntity; @@ -20,6 +21,7 @@ public function activateUser(User $user): User; /** * @throws ConflictException + * @throws NotFoundException * @throws RuntimeException */ public function createUser(array $data = []): User; @@ -44,13 +46,22 @@ public function emailExists(string $email = ''): bool; public function emailExistsOther(string $email = '', string $uuid = ''): bool; - public function findResetPasswordByHash(?string $hash): ?UserResetPasswordEntity; + /** + * @throws NotFoundException + */ + public function findResetPasswordByHash(?string $hash): UserResetPasswordEntity; - public function findByEmail(string $email): ?User; + /** + * @throws NotFoundException + */ + public function findByEmail(string $email): User; public function findByIdentity(string $identity): ?User; - public function findOneBy(array $params = []): ?User; + /** + * @throws NotFoundException + */ + public function findOneBy(array $params = []): User; public function getUsers(array $params = []): UserCollection;