|
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
|
|
|
|