zend-blog-3-backend

Форк
0
/
CommentController.php 
205 строк · 5.7 Кб
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: morontt
5
 * Date: 28.03.15
6
 * Time: 21:05
7
 */
8

9
namespace App\Controller\API;
10

11
use App\Controller\BaseController;
12
use App\Cron\Daily\CommentGeoLocation;
13
use App\Entity\Comment;
14
use App\Event\CommentEvent;
15
use App\Event\DeleteCommentEvent;
16
use App\Exception\NotAllowedCommentException;
17
use App\Form\CommentFormType;
18
use App\Repository\CommentRepository;
19
use App\Repository\ViewCommentRepository;
20
use App\Service\CommentManager;
21
use App\Service\Tracking;
22
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
23
use Symfony\Component\HttpFoundation\JsonResponse;
24
use Symfony\Component\HttpFoundation\Request;
25
use Symfony\Component\HttpFoundation\Response;
26
use Symfony\Component\Routing\Annotation\Route;
27
use Xelbot\Telegram\Robot;
28

29
/**
30
 * @Route("/api/comments")
31
 *
32
 * Class CommentController
33
 */
34
class CommentController extends BaseController
35
{
36
    protected array $errorsPathMap = [
37
        'children[text].data' => 'comment_text',
38
        'children[commentator].children[name].data' => 'name',
39
        'children[commentator].children[email].data' => 'email',
40
        'children[commentator].children[website].data' => 'website',
41
    ];
42

43
    /**
44
     * @Route("", methods={"GET"})
45
     *
46
     * @param Request $request
47
     * @param ViewCommentRepository $repository
48
     *
49
     * @return JsonResponse
50
     */
51
    public function findAllAction(Request $request, ViewCommentRepository $repository): JsonResponse
52
    {
53
        $pagination = $this->paginate(
54
            $repository->getListQuery(),
55
            $request->query->get('page', 1),
56
            30
57
        );
58

59
        $result = $this->getDataConverter()
60
            ->getCommentArray($pagination);
61

62
        return new JsonResponse($result);
63
    }
64

65
    /**
66
     * @Route("/{id}", requirements={"id": "\d+"}, methods={"GET"})
67
     *
68
     * @param Comment $entity
69
     *
70
     * @return JsonResponse
71
     */
72
    public function findAction(Comment $entity): JsonResponse
73
    {
74
        $result = $this->getDataConverter()
75
            ->getComment($entity);
76

77
        return new JsonResponse($result);
78
    }
79

80
    /**
81
     * @Route("", methods={"POST"})
82
     *
83
     * @param Request $request
84
     * @param Tracking $tracking
85
     * @param EventDispatcherInterface $dispatcher
86
     *
87
     * @throws \Doctrine\ORM\Exception\NotSupported
88
     *
89
     * @return JsonResponse
90
     */
91
    public function createAction(
92
        Request $request,
93
        Tracking $tracking,
94
        EventDispatcherInterface $dispatcher
95
    ): JsonResponse {
96
        $agent = $tracking->getTrackingAgent($request->server->get('HTTP_USER_AGENT'));
97

98
        $comment = new Comment();
99
        $comment
100
            ->setUser($this->getUser())
101
            ->setTrackingAgent($agent)
102
            ->setIpAddress($request->getClientIp())
103
        ;
104

105
        $commentData = $request->request->get('comment');
106
        if ($commentData['parent']) {
107
            $parent = $this->getEm()->getRepository(Comment::class)->find((int)$commentData['parent']);
108
            if ($parent) {
109
                $comment
110
                    ->setParent($parent)
111
                    ->setPost($parent->getPost())
112
                ;
113
            }
114
        }
115

116
        $this->getDataConverter()
117
            ->saveComment($comment, $commentData);
118

119
        $dispatcher->dispatch(new CommentEvent($comment));
120

121
        return new JsonResponse($this->getDataConverter()->getComment($comment), Response::HTTP_CREATED);
122
    }
123

124
    /**
125
     * @Route("/{id}", requirements={"id": "\d+"}, methods={"PUT"})
126
     *
127
     * @param Request $request
128
     * @param Comment $entity
129
     *
130
     * @return JsonResponse
131
     */
132
    public function updateAction(Request $request, Comment $entity): JsonResponse
133
    {
134
        $result = $this->getDataConverter()
135
            ->saveComment($entity, $request->request->get('comment'));
136

137
        return new JsonResponse($result);
138
    }
139

140
    /**
141
     * @Route("/{id}", requirements={"id": "\d+"}, methods={"DELETE"})
142
     *
143
     * @param Comment $entity
144
     * @param CommentRepository $repository
145
     * @param EventDispatcherInterface $dispatcher
146
     *
147
     * @return JsonResponse
148
     */
149
    public function deleteAction(
150
        Comment $entity,
151
        CommentRepository $repository,
152
        EventDispatcherInterface $dispatcher
153
    ): JsonResponse {
154
        $repository->markAsDeleted($entity);
155
        $dispatcher->dispatch(new DeleteCommentEvent($entity));
156

157
        return new JsonResponse(true);
158
    }
159

160
    /**
161
     * @Route("/geo-location", methods={"POST"})
162
     *
163
     * @param CommentGeoLocation $geoLocation
164
     * @param Robot $bot
165
     *
166
     * @return JsonResponse
167
     */
168
    public function getLocation(CommentGeoLocation $geoLocation, Robot $bot): JsonResponse
169
    {
170
        $geoLocation->run();
171
        $bot->sendMessage('CommentGeoLocation: ' . $geoLocation->getMessage());
172

173
        return new JsonResponse(true);
174
    }
175

176
    /**
177
     * @Route("/external", methods={"POST"})
178
     *
179
     * @param CommentManager $commentManager
180
     * @param Request $request
181
     *
182
     * @return JsonResponse
183
     */
184
    public function createExternalAction(CommentManager $commentManager, Request $request): JsonResponse
185
    {
186
        $form = $this->createForm(CommentFormType::class);
187
        $form->handleRequest($request);
188

189
        [$formData, $errors] = $this->handleForm($form);
190
        if ($errors) {
191
            return new JsonResponse($errors, Response::HTTP_UNPROCESSABLE_ENTITY);
192
        }
193

194
        try {
195
            $comment = $commentManager->saveExternalComment($formData);
196
        } catch (NotAllowedCommentException $e) {
197
            throw $this->createAccessDeniedException();
198
        }
199

200
        return new JsonResponse(
201
            $this->getDataConverter()->getComment($comment),
202
            Response::HTTP_CREATED
203
        );
204
    }
205
}
206

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.