src/Controller/Admin/ForumReponseCrudController.php line 234

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Admin;
  3. use App\Entity\ForumReponse;
  4. use App\Entity\Sujetforum;
  5. use App\Entity\User;
  6. use App\Form\CommentResponseForumType;
  7. use App\Repository\ForumReponseRepository;
  8. use App\Service\NotificationManager;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
  11. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  12. use EasyCorp\Bundle\EasyAdminBundle\Config\KeyValueStore;
  13. use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
  14. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
  15. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
  16. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  17. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  18. use EasyCorp\Bundle\EasyAdminBundle\Exception\ForbiddenActionException;
  19. use EasyCorp\Bundle\EasyAdminBundle\Exception\InsufficientEntityPermissionException;
  20. use EasyCorp\Bundle\EasyAdminBundle\Factory\EntityFactory;
  21. use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
  22. use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
  23. use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
  24. use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
  25. use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
  26. use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
  27. use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
  28. use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
  29. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  30. use EasyCorp\Bundle\EasyAdminBundle\Security\Permission;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use Symfony\Component\HttpFoundation\Response;
  33. use Symfony\Component\Routing\Annotation\Route;
  34. use Knp\Component\Pager\PaginatorInterface;
  35. use Symfony\Component\Security\Core\Security;
  36. use Symfony\Component\HttpFoundation\JsonResponse;
  37. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  38. use Symfony\Component\Validator\Constraints\DateTime;
  39. use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
  40. use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
  41. use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
  42. use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
  43. use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
  44. use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
  45. use Doctrine\ORM\QueryBuilder;
  46. class ForumReponseCrudController extends AbstractCrudController
  47. {
  48.     private $tokenStorage;
  49.     private $adminUrlGenerator;
  50.     private $notificationManager;
  51.         public function __construct(TokenStorageInterface $tokenStorage,
  52.         AdminUrlGenerator $adminUrlGeneratorNotificationManager $notificationManager)
  53.         {
  54.             $this->tokenStorage $tokenStorage;
  55.             $this->adminUrlGenerator $adminUrlGenerator;
  56.             $this->notificationManager $notificationManager;
  57.         }
  58.     public static function getEntityFqcn(): string
  59.     {
  60.         return ForumReponse::class;
  61.     }
  62.     public function configureCrud(Crud $crud): Crud
  63.     {
  64.         return $crud ->setPageTitle('index''Liste des Réponses')
  65.             ->setPageTitle('detail''Détails des Réponses')
  66.             ->setPageTitle('new''Créer une réponse');
  67.     }
  68.     public function configureActions(Actions $actions): Actions
  69.     {
  70.         $actions->add(Crud::PAGE_INDEXAction::DETAIL)
  71.         ->update(Crud::PAGE_INDEX,Action::NEW, function (Action $action) {
  72.             return $action->setLabel('Créer une reponse');
  73.         })
  74.         ->update(Crud::PAGE_NEWAction::SAVE_AND_RETURN, function (Action $action) {
  75.             return $action->setLabel('Enregistrer');
  76.         })
  77.         ->remove(Crud::PAGE_INDEXAction::DETAIL)
  78.         // ->remove(Crud::PAGE_INDEX, Action::NEW)
  79.         //->remove(Crud::PAGE_DETAIL, Action::EDIT)
  80.         ;
  81.         return $actions;
  82.     }
  83.     /**
  84.      * @param SearchDto $searchDto
  85.      * @param EntityDto $entityDto
  86.      * @param FieldCollection $fields
  87.      * @param FilterCollection $filters
  88.      * @return QueryBuilder
  89.      */
  90.     public function createIndexQueryBuilder(SearchDto $searchDtoEntityDto $entityDtoFieldCollection $fieldsFilterCollection $filters): QueryBuilder
  91.     {
  92.         $response parent::createIndexQueryBuilder($searchDto$entityDto$fields$filters); // TODO: Change the autogenerated stub
  93.         $response->andWhere('entity.parent IS NULL ');
  94.         $response->andWhere('entity.reponse IS NOT  NULL ');
  95.         $response->andWhere('entity.user IS NOT  NULL ');
  96.         return $response;
  97.     }
  98.     public function configureFields(string $pageName): iterable
  99.     {
  100.         return [
  101.             FormField::addTab('Détail Réponse')
  102.             ->setIcon('map')->addCssClass('optional'),
  103.             IdField::new('id')->hideOnForm(),
  104.             //TextField::new('nom','Nom')->formatValue(function ($value) { return $value ; }),
  105.             DateField::new('date''Date de la réponse')->formatValue(function ($value) {
  106.                 return $value ;
  107.             })->hideOnForm(),
  108.             AssociationField::new('user''utilisateur')->hideOnForm(),
  109.             AssociationField::new('sujetforum''Sujet'),
  110.             TextareaField::new('reponse''Réponse')->formatValue(function ($value) {
  111.                 return $value ;
  112.             }),
  113.      
  114.                
  115.             BooleanField::new('etat''Publier ?')
  116.                 // ->onlyOnForms() // Ne s'affiche que dans le formulaire
  117.                 ->setFormTypeOption('attr', ['class' => 'enable-in-form'])->setDisabled$pageName == Crud::PAGE_INDEX,true), // Ajout d'une classe CSS personnalisée
  118.   
  119.              FormField::addTab('Commentaires')
  120.              ->setIcon('map')->addCssClass('optional'),
  121.     
  122.              CollectionField::new('children')
  123.              ->allowAdd(true)
  124.              ->allowDelete(true)
  125.              ->setEntryIsComplex(true)
  126.              ->setLabel('comment')
  127.              ->setEntryType(CommentResponseForumType::class)
  128.             
  129.             
  130.              ->setFormTypeOptions(
  131.                  [
  132.                      'allow_add' => true,
  133.                      'allow_delete' => true,
  134.                      'form_attr' => 'ok',
  135.                      'label' => false,
  136.                      'auto_initialize' => false,
  137.                      'block_name' => null,
  138.                      'compound' => true,
  139.                      'by_reference' => false,
  140.              ]
  141.              )->hideOnIndex(false)->setLabel('Liste Commentaire')
  142.         
  143.         ];
  144.         DateField::new('date''Date de la réponse')->formatValue(function ($value) {
  145.             return $value ;
  146.         })->hideOnForm();
  147.     }
  148.     public function persistEntity(EntityManagerInterface $entityManager$entityInstance): void
  149.     {
  150.         $user $this->tokenStorage->getToken()->getUser();
  151.         $entityInstance->setUser($user);
  152.         $entityInstance->setDate(new \DateTime());
  153.         if ($entityInstance->getChildren()) {
  154.             /** mapping of created User */
  155.             foreach ($entityInstance->getChildren() as $child) {
  156.                 $child->setUser($user);
  157.                 $child->setDate(new \DateTime());
  158.                 $child->setEtat(true);
  159.                 $entityManager->persist($child);
  160.             }
  161.         }
  162.         $entityManager->persist($entityInstance);
  163.         $entityManager->flush();
  164.     }
  165.     public function updateEntity(EntityManagerInterface $entityManager$entityInstance): void
  166.     {
  167.         $conn $entityManager->getConnection();
  168.         $user $this->tokenStorage->getToken()->getUser();
  169.         $oldChildren = [];
  170.         /** check if children was updated */
  171.         foreach ($entityInstance->getChildren()->getSnapshot() as $child) {
  172.             /** check if there are children was removed */
  173.             if (!$entityInstance->getChildren()->contains($child)) {
  174.                 $entityManager->remove($child);
  175.             }
  176.             $sql 'SELECT * FROM forum_reponse f WHERE f.id = :id';
  177.             $resultSet $conn->executeQuery$sql, [ 'id' => $child->getId() ] );
  178.             $oldChildren$child->getId() ] = $resultSet->fetchAssociative();
  179.         }
  180.         /** mapping of created actionnaires */
  181.         foreach ($entityInstance->getChildren() as $child) {
  182.             if ( $child->getId() && array_key_exists($child->getId(), $oldChildren) ) {
  183.                 $child->setUser$entityManager->getRepositoryUser::class)->find$oldChildren$child->getId() ][ 'user_id' ] ) );
  184.                 $child->setDate( new \DateTime$oldChildren$child->getId() ][ 'date' ] ) );
  185.             }else{
  186.                 $child->setUser$user );
  187.                 $child->setDate( new \DateTime() );
  188.             }
  189.             $entityManager->persist($child);
  190.             if($child->isEtat()){
  191.                 $urlSujet '/show/forum/detail/'.$child->getSujetforum()->getId();
  192.                 $user $entityManager->getRepository(User::class)->find($child->getUser());
  193.                
  194.                 $notification_message 'Votre commentaire a été validé ! ';
  195.                 $this->notificationManager->pushMessage('Votre commentaire a été validé !'$notification_message$user$urlSujet);
  196.             }
  197.         }
  198.         if($entityInstance->isEtat()){
  199.             $urlSujet '/show/forum/detail/'.$entityInstance->getSujetforum()->getId();
  200.             $user $entityManager->getRepository(User::class)->find($entityInstance->getUser());
  201.            
  202.             $notification_message 'Votre réponse/commentaire a été validé ! ';
  203.             $this->notificationManager->pushMessage('Votre réponse/commentaire a été validé !'$notification_message$user$urlSujet);
  204.         }
  205.         $entityManager->flush();
  206.     }
  207.     #[Route('/show/forum/detail/{id}'name'show_forum_detail')]
  208.     public function listServices(Sujetforum $sujetRequest $requestEntityManagerInterface $entityManagerPaginatorInterface $paginatorSecurity $security): Response
  209.     {
  210.         if ($security->getUser()) {
  211.             $donnees $entityManager->getRepository(ForumReponse::class)->finResponsesdWithUser($sujet->getId(), $security->getUser()->getId(), 0);
  212.         } else {
  213.             
  214.             $donnees $entityManager->getRepository(ForumReponse::class)->finResponsesdWithUser($sujet->getId(), null 0);
  215.         }
  216.         $reponseForums $donnees;
  217.         return $this->render('forum/detail.html.twig', [
  218.              'sujetForum'=>$sujet,
  219.              'reponsesForums'=>$reponseForums
  220.           
  221.          ]);
  222.     }
  223.     
  224.     #[Route('/make/forum/response/{id}'name'make_forum_response')]
  225.     public function responseForum(Sujetforum $sujetRequest $request,
  226.      EntityManagerInterface $entityManagerSecurity $security,
  227.      NotificationManager $notificationManager
  228.      ): Response
  229.     
  230.         
  231.         if($this->getUser()){
  232.         $reponse= new ForumReponse();
  233.         $reponse->setReponse($request->request->get('message'));
  234.         $reponse->setUser($security->getUser());
  235.         $reponse->setDate(new \DateTime());
  236.         $reponse->setEtat(false);
  237.         $reponse->setSujetforum($sujet);
  238.         $entityManager->persist($reponse);
  239.         $entityManager->flush();
  240.            // Send Comment
  241.            $edit_demande_url =  $this->adminUrlGenerator
  242.            ->setController(ForumReponseCrudController::class)
  243.            ->setAction(Action::EDIT)
  244.            ->setEntityId($reponse->getId())
  245.            ->generateUrl();
  246.            $notification_message 'Nouvelle Réponse au Sujet ! ';
  247.            $admins $entityManager->getRepository(User::class)->findByRole('ROLE_ADMIN');
  248.            foreach($admins as $admin){
  249.                $notificationManager->pushMessage('Nouvelle Réponse au Sujet ! '$notification_message$admin$edit_demande_url);
  250.            }
  251.            // End send comment
  252.             return $this->redirectToRoute('show_forum_detail', ['id' => $sujet->getId()]);
  253.         }
  254.         else{
  255.             return $this->render('login/index.html.twig');
  256.         }
  257.     }
  258.     #[Route('/delete/forum/reponse/{id}'name'delete_forum_response')]
  259.     public function deleteResponseForum(ForumReponse $reponseRequest $requestEntityManagerInterface $entityManagerSecurity $security): JsonResponse
  260.     {
  261.         $entityManager->remove($reponse);
  262.         $entityManager->flush();
  263.         return new JsonResponse(['data' => 'done'], Response::HTTP_OK, ['Content-Type''application/json']);
  264.     }
  265.     #[Route('/make/forum/comment/{id}/{repid}'name'make_forum_comment')]
  266.     public function responseComment(Sujetforum $sujetint $repidRequest $requestEntityManagerInterface $entityManagerSecurity $security NotificationManager $notificationManager): Response
  267.     {
  268.         $parent $entityManager->getRepository(ForumReponse::class)->find($repid);
  269.         $reponse= new ForumReponse();
  270.         $reponse->setReponse($request->request->get('message'));
  271.         $reponse->setUser($security->getUser());
  272.         $reponse->setDate(new \DateTime());
  273.         $reponse->setEtat(false);
  274.         $reponse->setSujetforum($sujet);
  275.         $reponse->setParent($parent);
  276.         $entityManager->persist($reponse);
  277.         $entityManager->flush();
  278.         $edit_demande_url =  $this->adminUrlGenerator
  279.         ->setController(ForumReponseCrudController::class)
  280.         ->setAction(Action::EDIT)
  281.         ->setEntityId($repid)
  282.         ->generateUrl();
  283.         $notification_message 'Nouveau Commentaire  ! ';
  284.         $admins $entityManager->getRepository(User::class)->findByRole('ROLE_ADMIN');
  285.         foreach($admins as $admin){
  286.             $notificationManager->pushMessage('Nouveau Commentaire ! '$notification_message$admin$edit_demande_url);
  287.         }
  288.         return $this->redirectToRoute('show_forum_detail', ['id' => $sujet->getId()]);
  289.     }
  290.     #[Route('/update/forum/response/{id}'name'update_forum_response')]
  291.     public function updateResponseForum(ForumReponse $reponseRequest $requestEntityManagerInterface $entityManager): Response
  292.     {
  293.         $reponse->setReponse($request->request->get('message'));
  294.         $reponse->setDate(new \DateTime());
  295.         $entityManager->persist($reponse);
  296.         $entityManager->flush();
  297.         return $this->redirectToRoute('show_forum_detail', ['id' => $reponse->getSujetforum()->getId()]);
  298.     }
  299.     #[Route('/ajax/get/ReponseForum/{id}'name'show_forum_ReponseForum')]
  300.     public function ReponseForum(Sujetforum $sujetRequest $requestEntityManagerInterface $entityManagerPaginatorInterface $paginatorSecurity $security): JsonResponse
  301.     {
  302.         $offset = (int)$request->query->get('offset');
  303.       
  304.         if ($security->getUser()) {
  305.             $donnees $entityManager->getRepository(ForumReponse::class)->finResponsesdWithUser($sujet->getId(), $security->getUser()->getId(), $offset );
  306.         } else {
  307.             
  308.             $donnees $entityManager->getRepository(ForumReponse::class)->finResponsesdWithUser($sujet->getId(), null $offset);
  309.         }
  310.         $reponseForums $donnees;
  311.         foreach ($donnees as $key => $obj) {
  312.             $childrenData = [];
  313.             foreach ($obj->getChildren() as $child) {
  314.                 $childrenData[] = [
  315.                     'id' => $child->getId(),
  316.                     'date' => $child->getDate()->format('d/m/Y'),
  317.                     'userName' => $child->getUser()->getUsername(),
  318.                     'reponse' => $child->getReponse(),
  319.                     'userId' => $child->getUser()->getId(),
  320.                     'etat' => $child->isEtat(),
  321.                 ];
  322.             }
  323.         
  324.             $result[$key] = [
  325.                 'id' => $obj->getId(),
  326.                 'date' => $obj->getDate()->format('d/m/Y'),
  327.                 'userName' => $obj->getUser()->getUsername(),
  328.                 'userId' => $obj->getUser()->getId(),
  329.                 'reponse' => $obj->getReponse(),
  330.                 'etat' => $obj->isEtat(),
  331.                 'childs' => $childrenData,
  332.             ];
  333.         }
  334.         
  335.         return new JsonResponse([
  336.             'result'=>$result,
  337.             'reponsesForums'=>$reponseForums
  338.          
  339.         ], Response::HTTP_OK, ['Content-Type''application/json']);
  340.     }
  341. }