gamesshop/src/php/Routing/Api/DataTables/ProviderKeysEndpoint.php
2024-07-06 22:18:37 +02:00

78 lines
No EOL
2.4 KiB
PHP

<?php
declare(strict_types=1);
namespace GamesShop\Routing\Api\DataTables;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\Order;
use Doctrine\ORM\EntityManager;
use GamesShop\Entities\Account\User;
use GamesShop\Entities\Games\Game;
use GamesShop\Entities\Games\Key;
use GamesShop\Entities\GamesList;
use GamesShop\Login\LoginHandler;
use GamesShop\Login\UserPermission;
use Laminas\Diactoros\Response\JsonResponse;
use League\Route\Http\Exception\BadRequestException;
use League\Route\Http\Exception\ForbiddenException;
use League\Route\Http\Exception\UnauthorizedException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
final class ProviderKeysEndpoint
{
public function __construct(
private readonly LoginHandler $loginHandler,
private readonly EntityManager $entityManager,
)
{
}
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();
}
$body = $request->getQueryParams();
if (!array_key_exists('listid', $body)) {
throw new BadRequestException();
}
$list = $this->entityManager->getRepository(GamesList::class)->findOneBy([ 'owner' => $user, 'id' => $body['listid'] ]);
if (!$list instanceof GamesList) {
throw new BadRequestException();
}
$keys = $this->entityManager->getRepository(Key::class)->findBy(['list' => $list]);
$gameToKeyArray = [];
foreach ($keys as $key) {
$game = $key->getGame();
$id = $game->getId();
if (!array_key_exists($id, $gameToKeyArray)) {
$gameToKeyArray[$id] = [ $game, [] ];
}
$gameToKeyArray[$id][1][] = $key;
}
$result = [];
foreach ($gameToKeyArray as [$game, $keys]) {
$result[] = [
'gamePicture' => '',
'name' => $game->getName(),
'keysAmount' => count($keys),
'igdbState' => 'not implermented',
'keys' => $keys,
];
}
return new JsonResponse([ 'data' => $result ]);
}
}