|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace App\Controller\Comment; |
|
6
|
|
|
|
|
7
|
|
|
use App\Entity\Article; |
|
8
|
|
|
use App\Entity\Comment; |
|
9
|
|
|
use App\Form\CommentType; |
|
10
|
|
|
use App\Security\UserResolver; |
|
11
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
|
12
|
|
|
use FOS\RestBundle\Controller\Annotations\View; |
|
13
|
|
|
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; |
|
14
|
|
|
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; |
|
15
|
|
|
use Symfony\Component\Form\FormFactoryInterface; |
|
16
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
17
|
|
|
use Symfony\Component\Routing\Annotation\Route; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @Route("/api/articles/{slug}/comments", methods={"POST"}, name="api_comment_post") |
|
21
|
|
|
* |
|
22
|
|
|
* @View(statusCode=201) |
|
23
|
|
|
* |
|
24
|
|
|
* @Security("is_granted('ROLE_USER')") |
|
25
|
|
|
*/ |
|
26
|
|
|
final class CreateCommentController extends AbstractController |
|
27
|
|
|
{ |
|
28
|
|
|
private UserResolver $userResolver; |
|
29
|
|
|
private FormFactoryInterface $formFactory; |
|
30
|
|
|
private EntityManagerInterface $entityManager; |
|
31
|
|
|
|
|
32
|
4 |
|
public function __construct( |
|
33
|
|
|
UserResolver $userResolver, |
|
34
|
|
|
FormFactoryInterface $formFactory, |
|
35
|
|
|
EntityManagerInterface $entityManager |
|
36
|
|
|
) { |
|
37
|
4 |
|
$this->userResolver = $userResolver; |
|
38
|
4 |
|
$this->formFactory = $formFactory; |
|
39
|
4 |
|
$this->entityManager = $entityManager; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
3 |
|
public function __invoke(Request $request, Article $article): array |
|
43
|
|
|
{ |
|
44
|
3 |
|
$user = $this->userResolver->getCurrentUser(); |
|
45
|
|
|
|
|
46
|
3 |
|
$comment = new Comment(); |
|
47
|
3 |
|
$comment->setAuthor($user); |
|
48
|
3 |
|
$comment->setArticle($article); |
|
49
|
|
|
|
|
50
|
3 |
|
$form = $this->formFactory->createNamed('comment', CommentType::class, $comment); |
|
51
|
3 |
|
$form->submit($request->request->get('comment')); |
|
52
|
|
|
|
|
53
|
3 |
|
if ($form->isValid()) { |
|
54
|
1 |
|
$this->entityManager->persist($comment); |
|
55
|
1 |
|
$this->entityManager->flush(); |
|
56
|
|
|
|
|
57
|
1 |
|
return ['comment' => $comment]; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
2 |
|
return ['form' => $form]; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|