Implemented Code refactoring

MtoR

Freaky Coder
Staff member
Joined
Nov 14, 2015
Messages
3,904
You've extended the Thread Creator and Replier Services in your Core Add-on (which is used by this Add-on) in order to be able to automatically create threads/posts owned by a specific user:

This is not how things should be done in XF 2.

Example Code
Code:
/** @var \XF\Service\Thread\Replier $replier */
$replier = \XF::app()->service('XF:Thread\Replier', $thread);
$replier->setAutomatedUser($messagePoster);
$replier->setMessage($this->message, false);

$replier->getPost()->message_state = 'visible';

if ($replier && $replier->validate())
{
   $existingLastPostDate = $replier->getThread()->last_post_date;

   $post = $replier->save();

   if (\XF::visitor()->user_id && $post->Thread->getVisitorReadDate() >= $existingLastPostDate)
   {
       $this->repository('XF:Thread')->markThreadReadByVisitor($post->Thread);
   }
}
This (and other similar occurances) should be refactored as
Code:
$post = false;
$existingLastPostDate = $thread->last_post_date;

\XF::asVisitor($messagePoster, function () use ()
{
   /** @var \XF\Service\Thread\Replier $replier */
   $replier = \XF::app()->service('XF:Thread\Replier', $thread);
   $replier->setIsAutomated();
   $replier->setMessage($this->message, false);

   $replier->getPost()->message_state = 'visible';

   if ($replier && $replier->validate())
   {
       $post = $replier->save();
   }
}

if ($post !== false && \XF::visitor()->user_id && $thread->getVisitorReadDate() >= $existingLastPostDate)
{
   $this->repository('XF:Thread')->markThreadReadByVisitor($thread);
}
upload_2018-10-25_21-11-53.gif