SubscribeToPostWhenCommentPostedInForum.php 1.66 KB
<?php

namespace FootyRoom\Core\Subscription;

use FootyRoom\Core\ForumPost\ForumPostCommentPosted;
use FootyRoom\Queries\Subscription\OneSubscriptionQuery;
use FootyRoom\Queries\Subscription\SubscriptionQueryHandler;
use FootyRoom\Repositories\SubscriptionRepository;

class SubscribeToPostWhenCommentPostedInForum
{
    /**
     * @var \FootyRoom\Repositories\SubscriptionRepository
     */
    protected $subRepo;

    /**
     * @var \FootyRoom\Queries\Subscription\SubscriptionQueryHandler
     */
    protected $subQueryHandler;

    /**
     * Constructor.
     *
     * @param \FootyRoom\Repositories\SubscriptionRepository $subRepo
     * @param \FootyRoom\Queries\Subscription\SubscriptionQueryHandler $subQueryHandler
     */
    public function __construct(SubscriptionRepository $subRepo, SubscriptionQueryHandler $subQueryHandler)
    {
        $this->subRepo = $subRepo;
        $this->subQueryHandler = $subQueryHandler;
    }

    /**
     * Handler.
     *
     * @param \FootyRoom\Core\ForumPost\ForumPostCommentPosted $event
     */
    public function handle(ForumPostCommentPosted $event)
    {
        $postId = explode(':', $event->comment->getDiscussionId())[1];

        $subQuery = (new OneSubscriptionQuery())
            ->userId($event->comment->getAuthor()->getUserId())
            ->subjectType('post')
            ->subjectId($postId);

        if ($this->subQueryHandler->findOne($subQuery)) {
            return;
        }

        $subscription = new Subscription(
            $postId,
            'post',
            $event->comment->getAuthor()->getUserId()
        );

        $subscription->follow();

        $this->subRepo->create($subscription);
    }
}