CreateCommentAction::__invoke()   B
last analyzed

Complexity

Conditions 9
Paths 13

Size

Total Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 65
rs 7.208
c 0
b 0
f 0
cc 9
nc 13
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Form\FormFactoryInterface;
29
use Symfony\Component\Form\FormInterface;
30
use Symfony\Component\HttpFoundation\RedirectResponse;
31
use Symfony\Component\HttpFoundation\Request;
32
use Symfony\Component\HttpFoundation\Response;
33
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
34
use Symfony\Component\Routing\RouterInterface;
35
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
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.9',
95
                __CLASS__
96
            ), E_USER_DEPRECATED);
97
        }
98
    }
99
100
    /**
101
     * @param string $id
102
     *
103
     * @throws NotFoundHttpException
104
     *
105
     * @return Response
106
     */
107
    public function __invoke(Request $request, $id)
108
    {
109
        $post = $this->postManager->findOneBy([
110
            'id' => $id,
111
        ]);
112
113
        if (!$post instanceof PostInterface) {
114
            throw new NotFoundHttpException(sprintf('Post (%d) not found', $id));
115
        }
116
117
        if (!$post->isCommentable()) {
118
            // todo : add notice in event listener
119
            return new RedirectResponse($this->router->generate('sonata_news_view', [
120
                'permalink' => $this->blog->getPermalinkGenerator()->generate($post),
121
            ]));
122
        }
123
124
        $comment = $this->createComment($post);
125
126
        // NEXT_MAJOR: Remove the if code
127
        if (null !== $this->eventDispatcher) {
128
            $event = new GetResponseCommentEvent($comment, $request);
129
            $this->eventDispatcher->dispatch($event, SonataNewsEvents::COMMENT_INITIALIZE);
130
131
            if (null !== $event->getResponse()) {
132
                return $event->getResponse();
133
            }
134
        }
135
136
        $form = $this->getCommentForm($comment);
137
        $form->handleRequest($request);
138
139
        if ($form->isSubmitted() && $form->isValid()) {
140
            // NEXT_MAJOR: Remove the if code
141
            if (null !== $this->eventDispatcher) {
142
                $event = new FormEvent($form, $request);
143
                $this->eventDispatcher->dispatch($event, SonataNewsEvents::COMMENT_SUCCESS);
144
            }
145
146
            $comment = $form->getData();
147
148
            $this->commentManager->save($comment);
149
            $this->mailer->sendCommentNotification($comment);
150
151
            // todo : add notice in event listener
152
            $response = new RedirectResponse($this->router->generate('sonata_news_view', [
153
                'permalink' => $this->blog->getPermalinkGenerator()->generate($post),
154
            ]));
155
156
            // NEXT_MAJOR: Remove the if code
157
            if (null !== $this->eventDispatcher) {
158
                $this->eventDispatcher->dispatch(
159
                    new FilterCommentResponseEvent($comment, $request, $response),
160
                    SonataNewsEvents::COMMENT_COMPLETED
161
                );
162
            }
163
164
            return $response;
165
        }
166
167
        return $this->render('@SonataNews/Post/view.html.twig', [
168
            'post' => $post,
169
            'form' => $form,
170
        ]);
171
    }
172
173
    private function getCommentForm(CommentInterface $comment): FormInterface
174
    {
175
        return $this->formFactory->createNamed('comment', CommentType::class, $comment, [
176
            'action' => $this->router->generate('sonata_news_add_comment', [
177
                'id' => $comment->getPost()->getId(),
178
            ]),
179
            'method' => 'POST',
180
        ]);
181
    }
182
183
    private function createComment(PostInterface $post): CommentInterface
184
    {
185
        $comment = $this->commentManager->create();
186
        $comment->setPost($post);
187
        $comment->setStatus($post->getCommentsDefaultStatus());
188
189
        return $comment;
190
    }
191
}
192