Skip to content

Instantly share code, notes, and snippets.

@umpirsky
Created February 12, 2013 23:31
Show Gist options
  • Save umpirsky/4774504 to your computer and use it in GitHub Desktop.
Save umpirsky/4774504 to your computer and use it in GitHub Desktop.
<?php
class ThreadCountersListener implements EventSubscriberInterface
{
protected $commentManager;
public function __construct(CommentManagerInterface $commentManager)
{
$this->commentManager = $commentManager;
}
public function onCommentPersist(CommentEvent $event)
{
$comment = $event->getComment();
$thread = $comment->getThread();
$count = 0;
foreach ($this->commentManager->findCommentsByThread($thread) as $comment) {
var_dump($comment->getState());
if ($comment::STATE_VISIBLE == $comment->getState()) {
$count++;
}
}
$thread = $comment->getThread();
$thread->setNumComments($count);
$thread->setLastCommentAt($comment->getCreatedAt());
}
public static function getSubscribedEvents()
{
return array(Events::COMMENT_POST_PERSIST => 'onCommentPersist');
}
}
@ibasaw
Copy link

ibasaw commented Oct 16, 2013

i try this listener, but doesn't seem to work, count is always bad, it must count only valid comment

@karimsan
Copy link

You may try this

public function onCommentPersist(CommentEvent $event)
{
    $comment = $event->getComment();
    $thread = $comment->getThread();

    if (!$this->commentManager->isNewComment($comment)) {
        // if was invisible and now visible - increment counter
        if ( $comment->getState() == $comment::STATE_VISIBLE && $comment->getPreviousState() != $comment::STATE_VISIBLE ) {
            $thread->incrementNumComments(1);
        }
        // if was visible and now invisible - decrement counter
        elseif ( $comment->getState() != $comment::STATE_VISIBLE && $comment->getPreviousState() == $comment::STATE_VISIBLE ) {
            $thread->incrementNumComments(-1);
        }
        return;
    }

    if($comment->getState() === $comment::STATE_VISIBLE) {
        $thread->incrementNumComments(1);
    }
    $thread->setLastCommentAt($comment->getCreatedAt());
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment