Skip to content

Commit d90e0c1

Browse files
committed
minor #529 Use Post::addComment method to associate new comment with a post (voronkovich)
This PR was squashed before being merged into the master branch (closes #529). Discussion ---------- Use Post::addComment method to associate new comment with a post Commits ------- dce1e81 Use Post::addComment method to associate new comment with a post
2 parents 67fa51c + dce1e81 commit d90e0c1

File tree

3 files changed

+11
-6
lines changed

3 files changed

+11
-6
lines changed

src/AppBundle/Controller/BlogController.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,8 @@ public function commentNewAction(Request $request, Post $post)
9494
{
9595
$comment = new Comment();
9696
$comment->setAuthor($this->getUser());
97-
$comment->setPost($post);
97+
98+
$post->addComment($comment);
9899

99100
$form = $this->createForm(CommentType::class, $comment);
100101

src/AppBundle/DataFixtures/ORM/PostFixtures.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,10 @@ public function load(ObjectManager $manager)
6666
$comment->setAuthor($this->getReference('john-user'));
6767
$comment->setPublishedAt(new \DateTime('now + '.($i + $j).'seconds'));
6868
$comment->setContent($this->getRandomCommentContent());
69-
$comment->setPost($post);
7069

71-
$manager->persist($comment);
7270
$post->addComment($comment);
71+
72+
$manager->persist($comment);
7373
}
7474

7575
$manager->persist($post);

src/AppBundle/Entity/Post.php

+7-3
Original file line numberDiff line numberDiff line change
@@ -203,13 +203,17 @@ public function getComments()
203203

204204
public function addComment(Comment $comment)
205205
{
206-
$this->comments->add($comment);
207-
$comment->setPost($this);
206+
if (!$this->comments->contains($comment)) {
207+
$this->comments->add($comment);
208+
$comment->setPost($this);
209+
}
208210
}
209211

210212
public function removeComment(Comment $comment)
211213
{
212-
$this->comments->removeElement($comment);
214+
if ($this->comments->removeElement($comment)) {
215+
$comment->setPost(null);
216+
}
213217
}
214218

215219
public function getSummary()

0 commit comments

Comments
 (0)