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->getObject();
$entityManager = $args->getObjectManager();
if ($entity instanceof Post) {
$post = $entity;
$thread = $post->getThread();
$category = $thread->getCategory();
$category->setLastPostThreadTitle($thread->getTitle());
$category->setLastPostThreadSlug($thread->getSlug());
$category->setLastPostBody($post->getBody());
$category->setLastPosterUsername($post->getUser()->getUsername());
$category->setLastPostCreatedAt($post->getCreatedAt());
$category->setIsLastPostOp(false);
$category->setPosts($category->getPosts() + 1);
$entityManager->merge($category);
$entityManager->flush();
}
if ($entity instanceof Thread) {
$thread = $entity;
$category = $thread->getCategory();
$category->setLastPostThreadTitle($thread->getTitle());
$category->setLastPostThreadSlug($thread->getSlug());
$category->setLastPostBody($thread->getBody());
$category->setLastPosterUsername($thread->getUser()->getUsername());
$category->setLastPostCreatedAt($thread->getCreatedAt());
$category->setIsLastPostOp(true);
$entityManager->merge($category);
$entityManager->flush();
}
}
How would be possible to refactor this code to avoid WET?