Completed
Push — master ( ee87ec...477f2c )
by Grégoire
13s queued 10s
created

CreateCommentAction::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 9.536
c 0
b 0
f 0
cc 2
nc 2
nop 7
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\NewsBundle\Action;
15
16
use Sonata\NewsBundle\Event\FilterCommentResponseEvent;
17
use Sonata\NewsBundle\Event\FormEvent;
18
use Sonata\NewsBundle\Event\GetResponseCommentEvent;
19
use Sonata\NewsBundle\Form\Type\CommentType;
20
use Sonata\NewsBundle\Mailer\MailerInterface;
21
use Sonata\NewsBundle\Model\BlogInterface;
22
use Sonata\NewsBundle\Model\CommentInterface;
23
use Sonata\NewsBundle\Model\CommentManagerInterface;
24
use Sonata\NewsBundle\Model\PostInterface;
25
use Sonata\NewsBundle\Model\PostManagerInterface;
26
use Sonata\NewsBundle\SonataNewsEvents;
27
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
28
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
29
use Symfony\Component\Form\FormFactoryInterface;
30
use Symfony\Component\Form\FormInterface;
31
use Symfony\Component\HttpFoundation\RedirectResponse;
32
use Symfony\Component\HttpFoundation\Request;
33
use Symfony\Component\HttpFoundation\Response;
34
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
35
use Symfony\Component\Routing\RouterInterface;
36
37
final class CreateCommentAction extends Controller
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...e\Controller\Controller has been deprecated with message: since Symfony 4.2, use "Symfony\Bundle\FrameworkBundle\Controller\AbstractController" instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
38
{
39
    /**
40
     * @var RouterInterface
41
     */
42
    private $router;
43
44
    /**
45
     * @var BlogInterface
46
     */
47
    private $blog;
48
49
    /**
50
     * @var PostManagerInterface
51
     */
52
    private $postManager;
53
54
    /**
55
     * @var CommentManagerInterface
56
     */
57
    private $commentManager;
58
59
    /**
60
     * @var FormFactoryInterface
61
     */
62
    private $formFactory;
63
64
    /**
65
     * @var MailerInterface
66
     */
67
    private $mailer;
68
69
    /**
70
     * @var EventDispatcherInterface|null
71
     */
72
    private $eventDispatcher;
73
74
    // NEXT_MAJOR: Make $eventDispatcher a required dependency
75
    public function __construct(
76
        RouterInterface $router,
77
        BlogInterface $blog,
78
        PostManagerInterface $postManager,
79
        CommentManagerInterface $commentManager,
80
        FormFactoryInterface $formFactory,
81
        MailerInterface $mailer,
82
        EventDispatcherInterface $eventDispatcher = null
83
    ) {
84
        $this->router = $router;
85
        $this->blog = $blog;
86
        $this->postManager = $postManager;
87
        $this->commentManager = $commentManager;
88
        $this->formFactory = $formFactory;
89
        $this->mailer = $mailer;
90
        $this->eventDispatcher = $eventDispatcher;
91
92
        if (null === $this->eventDispatcher) {
93
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
94
                'Not providing an event dispatcher to %s is deprecated since sonata-project/news-bundle 3.x',
95
                __CLASS__
96
            ), E_USER_DEPRECATED);
97
        }
98
    }
99
100
    /**
101
     * @param string  $id
102
     * @param Request $request
103
     *
104
     * @throws NotFoundHttpException
105
     *
106
     * @return Response
107
     */
108
    public function __invoke(Request $request, $id)
109
    {
110
        $post = $this->postManager->findOneBy([
111
            'id' => $id,
112
        ]);
113
114
        if (!$post instanceof PostInterface) {
115
            throw new NotFoundHttpException(sprintf('Post (%d) not found', $id));
116
        }
117
118
        if (!$post->isCommentable()) {
119
            // todo : add notice in event listener
120
            return new RedirectResponse($this->router->generate('sonata_news_view', [
121
                'permalink' => $this->blog->getPermalinkGenerator()->generate($post),
122
            ]));
123
        }
124
125
        $comment = $this->createComment($post);
126
127
        // NEXT_MAJOR: Remove the if code
128
        if (null !== $this->eventDispatcher) {
129
            $event = new GetResponseCommentEvent($comment, $request);
130
            $this->eventDispatcher->dispatch(SonataNewsEvents::COMMENT_INITIALIZE, $event);
131
132
            if (null !== $event->getResponse()) {
133
                return $event->getResponse();
134
            }
135
        }
136
137
        $form = $this->getCommentForm($comment);
138
        $form->handleRequest($request);
139
140
        if ($form->isSubmitted() && $form->isValid()) {
141
            // NEXT_MAJOR: Remove the if code
142
            if (null !== $this->eventDispatcher) {
143
                $event = new FormEvent($form, $request);
144
                $this->eventDispatcher->dispatch(SonataNewsEvents::COMMENT_SUCCESS, $event);
145
            }
146
147
            $comment = $form->getData();
148
149
            $this->commentManager->save($comment);
150
            $this->mailer->sendCommentNotification($comment);
151
152
            // todo : add notice in event listener
153
            $response = new RedirectResponse($this->router->generate('sonata_news_view', [
154
                'permalink' => $this->blog->getPermalinkGenerator()->generate($post),
155
            ]));
156
157
            // NEXT_MAJOR: Remove the if code
158
            if (null !== $this->eventDispatcher) {
159
                $this->eventDispatcher->dispatch(
160
                    SonataNewsEvents::COMMENT_COMPLETED,
161
                    new FilterCommentResponseEvent($comment, $request, $response)
162
                );
163
            }
164
165
            return $response;
166
        }
167
168
        return $this->render('@SonataNews/Post/view.html.twig', [
169
            'post' => $post,
170
            'form' => $form,
171
        ]);
172
    }
173
174
    private function getCommentForm(CommentInterface $comment): FormInterface
175
    {
176
        return $this->formFactory->createNamed('comment', CommentType::class, $comment, [
177
            'action' => $this->router->generate('sonata_news_add_comment', [
178
                'id' => $comment->getPost()->getId(),
179
            ]),
180
            'method' => 'POST',
181
        ]);
182
    }
183
184
    private function createComment(PostInterface $post): CommentInterface
185
    {
186
        $comment = $this->commentManager->create();
187
        $comment->setPost($post);
188
        $comment->setStatus($post->getCommentsDefaultStatus());
189
190
        return $comment;
191
    }
192
}
193