XF 2.0 How to properly use \XF::asVisitor

AndyB

Well-known member
I'm creating an add-on to prune old conversations. I have extended the Conversation controller and have the following PHP code:

PHP:
<?php

namespace Andy\ConversationsPrune\XF\Pub\Controller;

use XF\Mvc\ParameterBag;

class Conversation extends XFCP_Conversation
{
	public function actionPrune(ParameterBag $params)
	{
		$conversationId = 11;

		$userConv = $this->assertViewableUserConversation($conversationId);
		
		$conversation = $userConv->Master;

		$recipientState = 'deleted_ignored';

		$recipient = $userConv->Recipient;
		
		if ($recipient)
		{
			$recipient->recipient_state = $recipientState;
			$recipient->save();
		}

		return $this->redirect($this->buildLink('conversations'));
	}
}

The code works fine but it only works to set the $recipientState to me as I'm the $visitor. What I would like to do is use the \XF::asVisitor so that I can define the $visitor as any userId. I assume I need to put the \XF::asVisitor code around the

$userConv = $this->assertViewableUserConversation($conversationId);

line, but I'm not sure of the correct format.

Thank you.
 
\XF::asVisitor runs the swaps the global visitor object and then restores if to ensure everything runs under the correct user.

You should do the entire entity mutate operation in the same context.

PHP:
class Conversation extends XFCP_Conversation
{
    public function actionPrune(ParameterBag $params)
    {
        $conversationId = 11;
                $userId = 1;
                $user = $this->app()->finder('XF:User')->whereId($userId)->fetchOne();

        $retValue = \XF::asVisitor($user, function() use ($conversationId)
        {
            $userConv = $this->assertViewableUserConversation($conversationId);
       
            $conversation = $userConv->Master;

            $recipientState = 'deleted_ignored';

            $recipient = $userConv->Recipient;
       
            if ($recipient)
            {
                $recipient->recipient_state = $recipientState;
                $recipient->save();
            }
            return $userConv;
        });


        return $this->redirect($this->buildLink('conversations'));
    }
}
 
Top Bottom