zend-blog-3-backend
115 строк · 3.0 Кб
1<?php
2
3namespace App\Service;
4
5use App\DTO\CommentDTO;
6use App\Entity\Comment;
7use App\Event\CommentEvent;
8use App\Exception\NotAllowedCommentException;
9use App\Repository\CommentatorRepository;
10use App\Repository\CommentRepository;
11use App\Repository\PostRepository;
12use App\Repository\UserRepository;
13use Laminas\Filter\StripTags;
14use Symfony\Component\EventDispatcher\EventDispatcherInterface;
15
16class CommentManager
17{
18/**
19* @var Tracking
20*/
21private $tracking;
22
23/**
24* @var EventDispatcherInterface
25*/
26private $dispatcher;
27
28/**
29* @var CommentatorRepository
30*/
31private $commentatorRepo;
32
33/**
34* @var CommentRepository
35*/
36private $commentRepo;
37
38/**
39* @var PostRepository
40*/
41private $postRepo;
42
43/**
44* @var UserRepository
45*/
46private $userRepository;
47
48public function __construct(
49Tracking $tracking,
50EventDispatcherInterface $dispatcher,
51CommentatorRepository $commentatorRepo,
52CommentRepository $commentRepo,
53UserRepository $userRepository,
54PostRepository $postRepo
55) {
56$this->tracking = $tracking;
57$this->dispatcher = $dispatcher;
58$this->commentatorRepo = $commentatorRepo;
59$this->userRepository = $userRepository;
60$this->commentRepo = $commentRepo;
61$this->postRepo = $postRepo;
62}
63
64/**
65* @param CommentDTO $commentData
66*
67* @throws NotAllowedCommentException
68*
69* @return Comment
70*/
71public function saveExternalComment(CommentDTO $commentData): Comment
72{
73$agent = $commentData->userAgent ? $this->tracking->getTrackingAgent($commentData->userAgent) : null;
74
75$post = $this->postRepo->find($commentData->topicId);
76if (!($post && !$post->isDisableComments())) {
77throw new NotAllowedCommentException();
78}
79
80$filter = new StripTags([
81'allowTags' => ['a', 's', 'b', 'i', 'em', 'strong', 'img', 'p'],
82'allowAttribs' => ['src', 'href'],
83]);
84
85$comment = new Comment();
86$comment
87->setTrackingAgent($agent)
88->setIpAddress($commentData->ipAddress)
89->setText($filter->filter($commentData->text))
90->setPost($post)
91;
92
93if ($commentData->parentId > 0) {
94$parent = $this->commentRepo->find($commentData->parentId);
95if ($parent) {
96$comment->setParent($parent);
97}
98}
99
100if ($commentData->commentator) {
101$commentator = $this->commentatorRepo->findOrCreate($commentData->commentator);
102$comment->setCommentator($commentator);
103} elseif ($commentData->user && $user = $this->userRepository->find($commentData->user->id)) {
104$comment->setUser($user);
105} else {
106throw new \LogicException('Comment without sender');
107}
108
109$this->commentRepo->save($comment);
110
111$this->dispatcher->dispatch(new CommentEvent($comment));
112
113return $comment;
114}
115}
116