<?php
namespace App\Controller;
use App\Entity\Posts;
use App\Form\PostsType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
class PostsController extends AbstractController
{
#[Route('/crear-posts', name: 'app_crear-posts')]
public function index(Request $request, SluggerInterface $slugger): Response
{
$post = new Posts();
$form = $this->createForm(PostsType::class, $post);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$brochureFile = $form->get('foto')->getData();
// this condition is needed because the 'brochure' field is not required
// so the PDF file must be processed only when a file is uploaded
if ($brochureFile) {
$originalFilename = pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();
// Move the file to the directory where brochures are stored
try {
$brochureFile->move(
$this->getParameter('photos_directory'),
$newFilename
);
} catch (FileException $e) {
throw new \Exception('Ups! ha ocurrido un error'.$e);
}
// updates the 'brochureFilename' property to store the PDF file name
// instead of its contents
}
$post->setFoto($newFilename);
$user = $this->getUser();
$post->setUser($user);
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
return $this->redirectToRoute('app_dashboard');
}
return $this->render('posts/index.html.twig', [
'form' => $form->createView()
]);
}
#[Route('/post/{id}', name: 'app_post')]
public function verPost($id) {
$em = $this->getDoctrine()->getManager();
$post = $em->getRepository(Posts::class)->find($id);
return $this->render('posts/verPost.html.twig',['post'=>$post]);
}
#[Route('/misposts', name: 'app_misposts')]
public function misPosts() {
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$posts = $em->getRepository(Posts::class)->findby(['user'=>$user]);
return $this->render('posts/misPosts.html.twig',['posts'=>$posts]);
}
#[Route('/likes', name: 'app_likes', options: ['expose' => true] )]
public function likes(Request $request) {
if($request->isXmlHttpRequest()){
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$id = $request->request->get('id');
$post = $em->getRepository(Posts::class)->find($id);
$likes = $post->getLikes();
$likes .= $user->getId().',';
$post->setLikes($likes);
$em->flush();
return new JsonResponse(['likes'=>$likes]);
}else{
throw new \Exception('Error al recibir el like');
}
}
}