<?php
namespace App\Controller;
use App\Entity\BookMark;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/book_mark")
*/
class BookMarkController extends AbstractController
{
/**
* @Route("/add", name="book_mark_add", methods={"POST"})
*/
public function add(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('status' => 'error','message' => 'Access forbidden!'), 400);
}
if(isset($request->request))
{
$user = $this->getUser();
$path = $request->request->get('path');
$title = $request->request->get('title');
$bookMark = new BookMark();
$bookMark->setTitle($title);
$bookMark->setLink($path);
$bookMark->setUser($user);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($bookMark);
$entityManager->flush();
$response = array('status' => 'ok');
}
return new JsonResponse($response,200);
}
/**
* @Route("/remove", name="book_mark_remove", methods={"POST"})
*/
public function remove(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('status' => 'error','message' => 'Access forbidden!'), 400);
}
$response = array('status' => 'error');
if(isset($request->request))
{
$user = $this->getUser();
$path = $request->request->get('path');
$bookMark = $this->getDoctrine()->getRepository(BookMark::class)->findOneBy(['user'=>$user,'link'=>$path]);
if($bookMark)
{
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($bookMark);
$entityManager->flush();
$response = array('status' => 'ok');
}
}
return new JsonResponse($response,200);
}
/**
* @Route("/check", name="book_mark_check", methods={"GET"})
*/
public function check(Request $request)
{
/*
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('status' => 'error','message' => 'Access forbidden!'), 400);
}*/
$response = array('status' => 'error');
if(isset($request->request))
{
$user = $this->getUser();
$path = $request->query->get('path');
$bookMark = $this->getDoctrine()->getRepository(BookMark::class)->findOneBy(['user'=>$user,'link'=>$path]);
$checked = !empty($bookMark);
$response = array('status' => 'ok','checked' => $checked);
}
return new JsonResponse($response,200);
}
/**
* @Route("/list", name="bookmarks_list", methods={"GET"})
*/
public function list(): JsonResponse
{
$user = $this->getUser();
if (!$user) {
return new JsonResponse(['error' => 'User not authenticated'], 401);
}
$bookmarks = $this->getDoctrine()
->getRepository(BookMark::class)
->findBy(['user' => $user], ['id' => 'DESC'], 5);
$bookmarksArray = [];
foreach ($bookmarks as $bookmark) {
$bookmarksArray[] = [
'id' => $bookmark->getId(),
'title' => $bookmark->getTitle(38), // Assuming this method exists
'link' => $bookmark->getLink(),
];
}
return new JsonResponse($bookmarksArray);
}
}