Passed
Branch feature/comments (12b220)
by Stone
04:53
created

DeleteCommentController   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 12
dl 0
loc 34
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A deleteTrick() 0 18 4
A __construct() 0 3 1
1
<?php
2
3
namespace App\Controller\Comment;
4
5
use App\Entity\Comment;
6
use App\Event\Comment\CommentDeletedEvent;
7
use App\Exception\RedirectException;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
9
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
10
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\Routing\Annotation\Route;
13
14
/**
15
 * Class DeleteCommentController
16
 * @package App\Controller\Comment
17
 * @IsGranted("ROLE_USER")
18
 */
19
class DeleteCommentController extends AbstractController
20
{
21
22
    /**
23
     * @var EventDispatcherInterface
24
     */
25
    private $dispatcher;
26
27
    public function __construct(EventDispatcherInterface $dispatcher)
28
    {
29
        $this->dispatcher = $dispatcher;
30
    }
31
32
    /**
33
     * @Route("/comment/delete/{id}", name="comment.delete", methods={"POST"})
34
     */
35
    public function deleteTrick(Comment $comment, Request $request)
36
    {
37
        if(!($this->isGranted('ROLE_ADMIN') || $this->getUser()->getId() === $comment->getUser()->getId()))
38
        {
39
            Throw new RedirectException($this->generateUrl('trick.show', ['id'=> $comment->getTrick()->getId(), 'slug'=> $comment->getTrick()->getSlug()]),"You are not allowed to edit this comment");
40
        }
41
42
        $submittedToken = $request->request->get('_token');
43
        if (!$this->isCsrfTokenValid('delete-comment' . $comment->getId(), $submittedToken)) {
44
            throw new RedirectException($this->generateUrl('home'), 'Bad CSRF Token');
45
        }
46
47
        $trick = $comment->getTrick();
48
49
        $event = new CommentDeletedEvent($comment);
50
        $this->dispatcher->dispatch(CommentDeletedEvent::NAME, $event);
51
52
        return $this->redirectToRoute('trick.show',['id'=> $trick->getId(), 'slug' => $trick->getSlug()]);
53
    }
54
}