Passed
Branch develop (7f369c)
by Nicolas
04:24
created

CommentPostController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 93.33%

Importance

Changes 0
Metric Value
dl 0
loc 47
ccs 14
cts 15
cp 0.9333
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 18 3
A __construct() 0 4 1
1
<?php
2
3
namespace App\Controller\Api;
4
5
use App\Entity\Article;
6
use App\Entity\Comment;
7
use App\Entity\User;
8
use App\Form\CommentType;
9
use Doctrine\ORM\EntityManagerInterface;
10
use FOS\RestBundle\Controller\Annotations\View;
11
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
12
use Symfony\Component\Form\FormFactoryInterface;
13
use Symfony\Component\Form\FormInterface;
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\Routing\Annotation\Route;
16
use Symfony\Component\Security\Core\User\UserInterface;
17
18
/**
19
 * CommentPostController.
20
 *
21
 * @Route("/api/articles/{slug}/comments", name="api_comment_post")
22
 * @Method("POST")
23
 * @View(statusCode=201)
24
 */
25
class CommentPostController
26
{
27
    /**
28
     * @var FormFactoryInterface
29
     */
30
    protected $factory;
31
32
    /**
33
     * @var EntityManagerInterface
34
     */
35
    protected $manager;
36
37
    /**
38
     * @param FormFactoryInterface   $factory
39
     * @param EntityManagerInterface $manager
40
     */
41 1
    public function __construct(FormFactoryInterface $factory, EntityManagerInterface $manager)
42
    {
43 1
        $this->factory = $factory;
44 1
        $this->manager = $manager;
45 1
    }
46
47
    /**
48
     * @param UserInterface $user
49
     * @param Request       $request
50
     * @param Article       $article
51
     *
52
     * @return array|FormInterface
53
     */
54 1
    public function __invoke(UserInterface $user, Request $request, Article $article)
55
    {
56
        /** @var User $user */
57 1
        $comment = new Comment();
58 1
        $comment->setAuthor($user);
59 1
        $comment->setArticle($article);
60
61 1
        $form = $this->factory->createNamed('comment', CommentType::class, $comment);
62 1
        $form->handleRequest($request);
63
64 1
        if ($form->isSubmitted() && $form->isValid()) {
65 1
            $this->manager->persist($comment);
66 1
            $this->manager->flush();
67
68 1
            return ['comment' => $comment];
69
        }
70
71
        return $form;
72
    }
73
}
74