| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- <?php
- namespace App\Controller;
- use App\Entity\PrivateDiscussion;
- use App\Entity\PrivateMessage;
- use App\Entity\User;
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
- use Symfony\Component\HttpFoundation\Response;
- use Symfony\Component\Routing\Annotation\Route;
- class PrivateDiscussionsController extends AbstractController
- {
- #[Route('/private/discussions', name: 'private_discussions')]
- public function index(Request $request): Response
- {
- $session = $this->get('session');
- if (null === $session->get('user')) {
- return $this->redirectToRoute('home');
- }
- $formBuilder = $this->createFormBuilder();
- $formBuilder->add('text', \Symfony\Component\Form\Extension\Core\Type\TextType::class)
- ->add('username', \Symfony\Component\Form\Extension\Core\Type\TextType::class)
- ->setAction($this->generateUrl('private_discussions'));
- $form = $formBuilder->getForm();
- $em = $this->getDoctrine()->getManager();
- $repo_user = $em->getRepository(User::class);
- $user = $repo_user->findOneBy(array('username' => $session->get("user")));
- $private_discussions = array();
- foreach ($user->getPrivateDiscussions() as $pd) {
- $participants = $pd->getParticipants();
- if ($participants[0] == $user) {
- $participant = $participants[1];
- } else {
- $participant = $participants[0];
- }
- array_push($private_discussions, array($pd->getId() => $participant->getUsername()));
- }
- if ($request->getMethod() == 'POST') {
- $form->handleRequest($request);
- if ($form->isValid()) {
- $recept = $repo_user->findOneBy(array('username' => $form->get('username')->getData()));
- if (!$recept) {
- return new Response("Profil non existant");
- }
- $disc_found = false;
- foreach ($user->getPrivateDiscussions() as $disc) {
- if(in_array($recept, $disc->getParticipants()->getValues())) {
- $disc_found = true;
- break;
- }
- }
- if ($disc_found) {
- return new Response("Discussion existante");
- }
- $discussion = new PrivateDiscussion();
- $discussion->addParticipant($user);
- $discussion->addParticipant($recept);
- $dm = new PrivateMessage();
- $dm->setSender($user);
- $dm->setText($form->get('text')->getData());
- $discussion->addPrivateMessage($dm);
- $em->persist($dm);
- $em->persist($discussion);
- $em->flush();
- }
- }
- return $this->render('private_discussions/index.html.twig', [
- 'controller_name' => 'PrivateDiscussionsController',
- 'form' => $form->createView(),
- 'private_discussions' => $private_discussions,
- 'username' => $session->get('user'),
- ]);
- }
- }
|