Forum system implementation I have a function which does the following:


When new Post Entity is added some fields in Category table are updated.
When new Thread Entity is added the same fields in Category table are updated.


Because of this, some lines are completely the same.

public function postPersist(LifecycleEventArgs $args)
{
    $entity = $args-&gt;getObject();
    $entityManager = $args-&gt;getObjectManager();

    if ($entity instanceof Post) {
        $post = $entity;

        $thread = $post-&gt;getThread();

        $category = $thread-&gt;getCategory(); 
        $category-&gt;setLastPostThreadTitle($thread-&gt;getTitle()); 
        $category-&gt;setLastPostThreadSlug($thread-&gt;getSlug()); 
        $category-&gt;setLastPostBody($post-&gt;getBody());
        $category-&gt;setLastPosterUsername($post-&gt;getUser()-&gt;getUsername());
        $category-&gt;setLastPostCreatedAt($post-&gt;getCreatedAt());
        $category-&gt;setIsLastPostOp(false);
        $category-&gt;setPosts($category-&gt;getPosts() + 1);

        $entityManager-&gt;merge($category);           
        $entityManager-&gt;flush();
    }

    if ($entity instanceof Thread) {
        $thread = $entity;

        $category = $thread-&gt;getCategory(); 
        $category-&gt;setLastPostThreadTitle($thread-&gt;getTitle()); 
        $category-&gt;setLastPostThreadSlug($thread-&gt;getSlug()); 
        $category-&gt;setLastPostBody($thread-&gt;getBody());
        $category-&gt;setLastPosterUsername($thread-&gt;getUser()-&gt;getUsername());
        $category-&gt;setLastPostCreatedAt($thread-&gt;getCreatedAt());
        $category-&gt;setIsLastPostOp(true);

        $entityManager-&gt;merge($category);           
        $entityManager-&gt;flush();
    }
}


How would be possible to refactor this code to avoid WET?
How about something like this there is some checking that needs to be done because I inverse the $isPost bool and that could be buggy

public function postPersist(LifecycleEventArgs $args)
{
    $entity = $args-&gt;getObject();
    $entityManager = $args-&gt;getObjectManager();

    $isPost = $entity instanceof Post;

    $thread = $isPost ? $post-&gt;getThread() : $entity;

    $details = $isPost ? $entity : $thread;

    $category = $thread-&gt;getCategory(); 
    $category-&gt;setLastPostThreadTitle($thread-&gt;getTitle()); 
    $category-&gt;setLastPostThreadSlug($thread-&gt;getSlug()); 
    $category-&gt;setLastPostBody($details-&gt;getBody());
    $category-&gt;setLastPosterUsername($details-&gt;getUser()-&gt;getUsername());
    $category-&gt;setLastPostCreatedAt($details-&gt;getCreatedAt());

    //NOTE the inversion of the isPost bool
    //TODO Test this
    $category-&gt;setIsLastPostOp(!$isPost);

    if($isPost){         
        $category-&gt;setPosts($category-&gt;getPosts() + 1);
    }

    $entityManager-&gt;merge($category);           
    $entityManager-&gt;flush();
}