59 lines
No EOL
1.8 KiB
PHP
59 lines
No EOL
1.8 KiB
PHP
<?php
|
|
|
|
namespace GamesShop\Routing\Api\Web;
|
|
|
|
use Doctrine\Common\Collections\Criteria;
|
|
use Doctrine\ORM\EntityManager;
|
|
use GamesShop\Entities\Account\User;
|
|
use GamesShop\Login\LoginHandler;
|
|
use GamesShop\Login\UserPermission;
|
|
use Laminas\Diactoros\Response\JsonResponse;
|
|
use League\Route\Http\Exception\ForbiddenException;
|
|
use League\Route\Http\Exception\UnauthorizedException;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
|
|
final class SearchForUsers
|
|
{
|
|
public function __construct(
|
|
private readonly LoginHandler $loginHandler,
|
|
private readonly EntityManager $entityManager,
|
|
) { }
|
|
|
|
/**
|
|
* @throws ForbiddenException
|
|
* @throws UnauthorizedException
|
|
*/
|
|
public function __invoke(ServerRequestInterface $request): ResponseInterface
|
|
{
|
|
if (!$this->loginHandler->isLoggedIn()) {
|
|
throw new UnauthorizedException();
|
|
}
|
|
|
|
$user = $this->loginHandler->getCurrentUser();
|
|
if (!$user->getPermission()->hasLevel(UserPermission::PROVIDER)) {
|
|
throw new ForbiddenException();
|
|
}
|
|
|
|
$searchQuery = $request->getQueryParams()['query'] ?? '';
|
|
|
|
$repo = $this->entityManager->getRepository(User::class);
|
|
|
|
$criteria = Criteria::create();
|
|
$criteria->where(Criteria::expr()->contains('name', $searchQuery));
|
|
$criteria->setMaxResults(10);
|
|
|
|
$values = $repo->matching($criteria);
|
|
return new JsonResponse(
|
|
$values
|
|
->filter(fn ($value) => $value !== $user)
|
|
->map(function (User $user) {
|
|
return [
|
|
'value' => $user->getId(),
|
|
'label' => $user->getName()
|
|
];
|
|
})
|
|
->toArray()
|
|
);
|
|
}
|
|
} |