<?php
namespace App\Http\Controller\Api\V2\ActiveSession;
use App\Database\Domain\Entity\Sessions\ActiveSessions\ActiveSessionTab;
use App\Database\Domain\Repository\ActiveDeviceRepository;
use App\Infrastructure\FileManager\FileSystem;
use App\Infrastructure\Util\Identifier;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* @Route("/api/v2/active-session/devices/replace-links", name="api_v2_active_session_replace_tabs", methods={"PATCH"})
*/
class ReplaceTabsAction extends AbstractController
{
public function __invoke(Request $request, ActiveDeviceRepository $activeDeviceRepository, EntityManagerInterface $em, FileSystem $fileSystem)
{
$activeDevice = $activeDeviceRepository->findOneBy(['deviceId' => $request->headers->get('BROWSER-ID'), 'user' => $this->getUser()]);
if (null === $activeDevice) {
throw new NotFoundHttpException('device was not found');
}
if ($activeDevice->getUser()->getId() !== $this->getUser()->getId()) {
throw new AccessDeniedException();
}
if (!$activeDevice->isSyncEnabled()) {
throw new AccessDeniedException('Sync is disabled for this device');
}
foreach ($activeDevice->getTabs() as $tab) {
$em->remove($tab);
}
$data = json_decode($request->getContent(), true);
foreach ($data['links'] as $index => $newTab) {
$icon = $newTab['icon'] ?? null;
if (empty($icon)) {
$icons = $fileSystem->getFilesList('/link-icons');
$icon = $_ENV['APP_HOST'].'/link-icons/'.$icons[rand(0, count($icons) - 1)];
}
$tab = new ActiveSessionTab(
Identifier::generate(),
$activeDevice,
$newTab['name'],
$newTab['url'],
$icon
);
$tab->setOrderIndex($index);
$tab->setIsPin($newTab['is_pin'] ?? false);
$em->persist($tab);
}
$em->flush();
return $this->json([]);
}
}