<?php
namespace Nellapp\Bundle\SDKBundle\Permission\Controller\Async;
use Nellapp\Bundle\SDKBundle\Auth\Entity\UserInterface;
use Nellapp\Bundle\SDKBundle\Channel\Entity\ChannelInterface;
use Nellapp\Bundle\SDKBundle\GlobalGetters\GlobalEntitiesService;
use Nellapp\Bundle\SDKBundle\Permission\ChannelResourceManager;
use Nellapp\Bundle\SDKBundle\Permission\Security\Authorization\AuthorizationHelper;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class ChannelResourceAccessCacheController extends AbstractController
{
public function __construct(
private GlobalEntitiesService $globalEntitiesService,
private ChannelResourceManager $channelResourceManager,
private AuthorizationHelper $authorizationHelper,
)
{
}
public function __invoke(Request $request, string $channelId, string $userId): JsonResponse
{
$channel = $this->getChannel($channelId);
if (!$channel) {
throw new NotFoundHttpException('');
}
$user = $this->getUserCheck($userId);
if (!$user) {
throw new NotFoundHttpException('');
}
$resourceClass = $this->getResourceClass($request);
if (!$resourceClass) {
throw new NotFoundHttpException('');
}
$permCheck = $this->getPermCheck($request);
if (!$permCheck) {
throw new NotFoundHttpException('');
}
$data = json_decode($request->getContent(), true);
if (!isset($data['ids']) || !is_array($data['ids'])) {
throw new BadRequestHttpException();
}
$channelResourceRepository = $this->channelResourceManager->getChannelResourceRepository($resourceClass);
if (!$channelResourceRepository) {
throw new BadRequestHttpException();
}
$qb = $channelResourceRepository->queryByChannel($channel);
$iterable = $qb->andWhere($qb->getRootAliases()[0] . '.id IN (:ids)')
->setParameter('ids', $data['ids'])
->getQuery()
->toIterable();
$accessibleIds = [];
foreach ($iterable as $resource) {
if ($this->authorizationHelper->isUserGranted($user, $permCheck, $resource)) {
$accessibleIds[] = $resource->getId();
}
}
return new JsonResponse(['accessibleIds' => $accessibleIds]);
}
private function getChannel(string $channelId): ?ChannelInterface
{
return $this->globalEntitiesService->getChannelRepository()->find($channelId);
}
private function getUserCheck(string $userId): ?UserInterface
{
return $this->globalEntitiesService->getUserRepository()->find($userId);
}
public function getResourceClass(Request $request): string
{
return $request->attributes->get('_resource_class');
}
public function getPermCheck(Request $request): string
{
return $request->attributes->get('_perm_check');
}
}