<?php
namespace App\Controller\Admin;
use App\Entity\ForumReponse;
use App\Entity\Sujetforum;
use App\Entity\User;
use App\Form\CommentResponseForumType;
use App\Repository\ForumReponseRepository;
use App\Service\NotificationManager;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\KeyValueStore;
use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Exception\ForbiddenActionException;
use EasyCorp\Bundle\EasyAdminBundle\Exception\InsufficientEntityPermissionException;
use EasyCorp\Bundle\EasyAdminBundle\Factory\EntityFactory;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use EasyCorp\Bundle\EasyAdminBundle\Security\Permission;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Validator\Constraints\DateTime;
use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
use Doctrine\ORM\QueryBuilder;
class ForumReponseCrudController extends AbstractCrudController
{
private $tokenStorage;
private $adminUrlGenerator;
private $notificationManager;
public function __construct(TokenStorageInterface $tokenStorage,
AdminUrlGenerator $adminUrlGenerator, NotificationManager $notificationManager)
{
$this->tokenStorage = $tokenStorage;
$this->adminUrlGenerator = $adminUrlGenerator;
$this->notificationManager = $notificationManager;
}
public static function getEntityFqcn(): string
{
return ForumReponse::class;
}
public function configureCrud(Crud $crud): Crud
{
return $crud ->setPageTitle('index', 'Liste des Réponses')
->setPageTitle('detail', 'Détails des Réponses')
->setPageTitle('new', 'Créer une réponse');
}
public function configureActions(Actions $actions): Actions
{
$actions->add(Crud::PAGE_INDEX, Action::DETAIL)
->update(Crud::PAGE_INDEX,Action::NEW, function (Action $action) {
return $action->setLabel('Créer une reponse');
})
->update(Crud::PAGE_NEW, Action::SAVE_AND_RETURN, function (Action $action) {
return $action->setLabel('Enregistrer');
})
->remove(Crud::PAGE_INDEX, Action::DETAIL)
// ->remove(Crud::PAGE_INDEX, Action::NEW)
//->remove(Crud::PAGE_DETAIL, Action::EDIT)
;
return $actions;
}
/**
* @param SearchDto $searchDto
* @param EntityDto $entityDto
* @param FieldCollection $fields
* @param FilterCollection $filters
* @return QueryBuilder
*/
public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
{
$response = parent::createIndexQueryBuilder($searchDto, $entityDto, $fields, $filters); // TODO: Change the autogenerated stub
$response->andWhere('entity.parent IS NULL ');
$response->andWhere('entity.reponse IS NOT NULL ');
$response->andWhere('entity.user IS NOT NULL ');
return $response;
}
public function configureFields(string $pageName): iterable
{
return [
FormField::addTab('Détail Réponse')
->setIcon('map')->addCssClass('optional'),
IdField::new('id')->hideOnForm(),
//TextField::new('nom','Nom')->formatValue(function ($value) { return $value ; }),
DateField::new('date', 'Date de la réponse')->formatValue(function ($value) {
return $value ;
})->hideOnForm(),
AssociationField::new('user', 'utilisateur')->hideOnForm(),
AssociationField::new('sujetforum', 'Sujet'),
TextareaField::new('reponse', 'Réponse')->formatValue(function ($value) {
return $value ;
}),
BooleanField::new('etat', 'Publier ?')
// ->onlyOnForms() // Ne s'affiche que dans le formulaire
->setFormTypeOption('attr', ['class' => 'enable-in-form'])->setDisabled( $pageName == Crud::PAGE_INDEX,true), // Ajout d'une classe CSS personnalisée
FormField::addTab('Commentaires')
->setIcon('map')->addCssClass('optional'),
CollectionField::new('children')
->allowAdd(true)
->allowDelete(true)
->setEntryIsComplex(true)
->setLabel('comment')
->setEntryType(CommentResponseForumType::class)
->setFormTypeOptions(
[
'allow_add' => true,
'allow_delete' => true,
'form_attr' => 'ok',
'label' => false,
'auto_initialize' => false,
'block_name' => null,
'compound' => true,
'by_reference' => false,
]
)->hideOnIndex(false)->setLabel('Liste Commentaire')
];
DateField::new('date', 'Date de la réponse')->formatValue(function ($value) {
return $value ;
})->hideOnForm();
}
public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$user = $this->tokenStorage->getToken()->getUser();
$entityInstance->setUser($user);
$entityInstance->setDate(new \DateTime());
if ($entityInstance->getChildren()) {
/** mapping of created User */
foreach ($entityInstance->getChildren() as $child) {
$child->setUser($user);
$child->setDate(new \DateTime());
$child->setEtat(true);
$entityManager->persist($child);
}
}
$entityManager->persist($entityInstance);
$entityManager->flush();
}
public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$conn = $entityManager->getConnection();
$user = $this->tokenStorage->getToken()->getUser();
$oldChildren = [];
/** check if children was updated */
foreach ($entityInstance->getChildren()->getSnapshot() as $child) {
/** check if there are children was removed */
if (!$entityInstance->getChildren()->contains($child)) {
$entityManager->remove($child);
}
$sql = 'SELECT * FROM forum_reponse f WHERE f.id = :id';
$resultSet = $conn->executeQuery( $sql, [ 'id' => $child->getId() ] );
$oldChildren[ $child->getId() ] = $resultSet->fetchAssociative();
}
/** mapping of created actionnaires */
foreach ($entityInstance->getChildren() as $child) {
if ( $child->getId() && array_key_exists($child->getId(), $oldChildren) ) {
$child->setUser( $entityManager->getRepository( User::class)->find( $oldChildren[ $child->getId() ][ 'user_id' ] ) );
$child->setDate( new \DateTime( $oldChildren[ $child->getId() ][ 'date' ] ) );
}else{
$child->setUser( $user );
$child->setDate( new \DateTime() );
}
$entityManager->persist($child);
if($child->isEtat()){
$urlSujet = '/show/forum/detail/'.$child->getSujetforum()->getId();
$user = $entityManager->getRepository(User::class)->find($child->getUser());
$notification_message = 'Votre commentaire a été validé ! ';
$this->notificationManager->pushMessage('Votre commentaire a été validé !', $notification_message, $user, $urlSujet);
}
}
if($entityInstance->isEtat()){
$urlSujet = '/show/forum/detail/'.$entityInstance->getSujetforum()->getId();
$user = $entityManager->getRepository(User::class)->find($entityInstance->getUser());
$notification_message = 'Votre réponse/commentaire a été validé ! ';
$this->notificationManager->pushMessage('Votre réponse/commentaire a été validé !', $notification_message, $user, $urlSujet);
}
$entityManager->flush();
}
#[Route('/show/forum/detail/{id}', name: 'show_forum_detail')]
public function listServices(Sujetforum $sujet, Request $request, EntityManagerInterface $entityManager, PaginatorInterface $paginator, Security $security): Response
{
if ($security->getUser()) {
$donnees = $entityManager->getRepository(ForumReponse::class)->finResponsesdWithUser($sujet->getId(), $security->getUser()->getId(), 0);
} else {
$donnees = $entityManager->getRepository(ForumReponse::class)->finResponsesdWithUser($sujet->getId(), null , 0);
}
$reponseForums = $donnees;
return $this->render('forum/detail.html.twig', [
'sujetForum'=>$sujet,
'reponsesForums'=>$reponseForums
]);
}
#[Route('/make/forum/response/{id}', name: 'make_forum_response')]
public function responseForum(Sujetforum $sujet, Request $request,
EntityManagerInterface $entityManager, Security $security,
NotificationManager $notificationManager
): Response
{
if($this->getUser()){
$reponse= new ForumReponse();
$reponse->setReponse($request->request->get('message'));
$reponse->setUser($security->getUser());
$reponse->setDate(new \DateTime());
$reponse->setEtat(false);
$reponse->setSujetforum($sujet);
$entityManager->persist($reponse);
$entityManager->flush();
// Send Comment
$edit_demande_url = $this->adminUrlGenerator
->setController(ForumReponseCrudController::class)
->setAction(Action::EDIT)
->setEntityId($reponse->getId())
->generateUrl();
$notification_message = 'Nouvelle Réponse au Sujet ! ';
$admins = $entityManager->getRepository(User::class)->findByRole('ROLE_ADMIN');
foreach($admins as $admin){
$notificationManager->pushMessage('Nouvelle Réponse au Sujet ! ', $notification_message, $admin, $edit_demande_url);
}
// End send comment
return $this->redirectToRoute('show_forum_detail', ['id' => $sujet->getId()]);
}
else{
return $this->render('login/index.html.twig');
}
}
#[Route('/delete/forum/reponse/{id}', name: 'delete_forum_response')]
public function deleteResponseForum(ForumReponse $reponse, Request $request, EntityManagerInterface $entityManager, Security $security): JsonResponse
{
$entityManager->remove($reponse);
$entityManager->flush();
return new JsonResponse(['data' => 'done'], Response::HTTP_OK, ['Content-Type', 'application/json']);
}
#[Route('/make/forum/comment/{id}/{repid}', name: 'make_forum_comment')]
public function responseComment(Sujetforum $sujet, int $repid, Request $request, EntityManagerInterface $entityManager, Security $security , NotificationManager $notificationManager): Response
{
$parent = $entityManager->getRepository(ForumReponse::class)->find($repid);
$reponse= new ForumReponse();
$reponse->setReponse($request->request->get('message'));
$reponse->setUser($security->getUser());
$reponse->setDate(new \DateTime());
$reponse->setEtat(false);
$reponse->setSujetforum($sujet);
$reponse->setParent($parent);
$entityManager->persist($reponse);
$entityManager->flush();
$edit_demande_url = $this->adminUrlGenerator
->setController(ForumReponseCrudController::class)
->setAction(Action::EDIT)
->setEntityId($repid)
->generateUrl();
$notification_message = 'Nouveau Commentaire ! ';
$admins = $entityManager->getRepository(User::class)->findByRole('ROLE_ADMIN');
foreach($admins as $admin){
$notificationManager->pushMessage('Nouveau Commentaire ! ', $notification_message, $admin, $edit_demande_url);
}
return $this->redirectToRoute('show_forum_detail', ['id' => $sujet->getId()]);
}
#[Route('/update/forum/response/{id}', name: 'update_forum_response')]
public function updateResponseForum(ForumReponse $reponse, Request $request, EntityManagerInterface $entityManager): Response
{
$reponse->setReponse($request->request->get('message'));
$reponse->setDate(new \DateTime());
$entityManager->persist($reponse);
$entityManager->flush();
return $this->redirectToRoute('show_forum_detail', ['id' => $reponse->getSujetforum()->getId()]);
}
#[Route('/ajax/get/ReponseForum/{id}', name: 'show_forum_ReponseForum')]
public function ReponseForum(Sujetforum $sujet, Request $request, EntityManagerInterface $entityManager, PaginatorInterface $paginator, Security $security): JsonResponse
{
$offset = (int)$request->query->get('offset');
if ($security->getUser()) {
$donnees = $entityManager->getRepository(ForumReponse::class)->finResponsesdWithUser($sujet->getId(), $security->getUser()->getId(), $offset );
} else {
$donnees = $entityManager->getRepository(ForumReponse::class)->finResponsesdWithUser($sujet->getId(), null , $offset);
}
$reponseForums = $donnees;
foreach ($donnees as $key => $obj) {
$childrenData = [];
foreach ($obj->getChildren() as $child) {
$childrenData[] = [
'id' => $child->getId(),
'date' => $child->getDate()->format('d/m/Y'),
'userName' => $child->getUser()->getUsername(),
'reponse' => $child->getReponse(),
'userId' => $child->getUser()->getId(),
'etat' => $child->isEtat(),
];
}
$result[$key] = [
'id' => $obj->getId(),
'date' => $obj->getDate()->format('d/m/Y'),
'userName' => $obj->getUser()->getUsername(),
'userId' => $obj->getUser()->getId(),
'reponse' => $obj->getReponse(),
'etat' => $obj->isEtat(),
'childs' => $childrenData,
];
}
return new JsonResponse([
'result'=>$result,
'reponsesForums'=>$reponseForums
], Response::HTTP_OK, ['Content-Type', 'application/json']);
}
}