Passed
Branch develop (f6de6e)
by Nicolas
04:27
created

CommentPostController::__invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 2
dl 0
loc 19
ccs 12
cts 12
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace App\Controller\Api;
4
5
use App\Entity\Article;
6
use App\Entity\Comment;
7
use App\Form\CommentType;
8
use App\Security\UserResolver;
9
use Doctrine\ORM\EntityManagerInterface;
10
use FOS\RestBundle\Controller\Annotations\View;
11
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
13
use Symfony\Component\Form\FormFactoryInterface;
14
use Symfony\Component\Form\FormInterface;
15
use Symfony\Component\HttpFoundation\Request;
16
use Symfony\Component\Routing\Annotation\Route;
17
18
/**
19
 * @Route("/api/articles/{slug}/comments", name="api_comment_post")
20
 * @Method("POST")
21
 *
22
 * @View(statusCode=201)
23
 *
24
 * @Security("is_granted('ROLE_USER')")
25
 */
26
final class CommentPostController
27
{
28
    /**
29
     * @var FormFactoryInterface
30
     */
31
    private $formFactory;
32
33
    /**
34
     * @var EntityManagerInterface
35
     */
36
    private $entityManager;
37
38
    /**
39
     * @var UserResolver
40
     */
41
    private $userResolver;
42
43
    /**
44
     * @param FormFactoryInterface   $formFactory
45
     * @param EntityManagerInterface $entityManager
46
     * @param UserResolver           $userResolver
47
     */
48 2
    public function __construct(
49
        FormFactoryInterface $formFactory,
50
        EntityManagerInterface $entityManager,
51
        UserResolver $userResolver
52
    ) {
53 2
        $this->formFactory = $formFactory;
54 2
        $this->entityManager = $entityManager;
55 2
        $this->userResolver = $userResolver;
56 2
    }
57
58
    /**
59
     * @param Request $request
60
     * @param Article $article
61
     *
62
     * @throws \Exception
63
     *
64
     * @return array|FormInterface
65
     */
66 1
    public function __invoke(Request $request, Article $article)
67
    {
68 1
        $user = $this->userResolver->getCurrentUser();
69
70 1
        $comment = new Comment();
71 1
        $comment->setAuthor($user);
72 1
        $comment->setArticle($article);
73
74 1
        $form = $this->formFactory->createNamed('comment', CommentType::class, $comment);
75 1
        $form->submit($request->request->get('comment'));
76
77 1
        if ($form->isValid()) {
78 1
            $this->entityManager->persist($comment);
79 1
            $this->entityManager->flush();
80
81 1
            return ['comment' => $comment];
82
        }
83
84 1
        return $form;
85
    }
86
}
87