EditCommentHandler.php 2.55 KB
<?php

namespace FootyRoom\App\Comment;

use FootyRoom\User\User;
use FootyRoom\Core\CoreException;
use FootyRoom\Core\Comment\CommentPolicy;
use Illuminate\Contracts\Events\Dispatcher;
use FootyRoom\Repositories\CommentRepository;

class EditCommentHandler
{
    /**
     * @var \FootyRoom\Core\Comment\CommentingService
     */
    protected $commentingService;

    /**
     * @var \Illuminate\Contracts\Events\Dispatcher
     */
    protected $events;

    /**
     * @var \FootyRoom\Core\Comment\CommentPolicy
     */
    protected $commentPolicy;

    /**
     * @var \FootyRoom\Repositories\CommentRepository
     */
    protected $commentRepo;

    /**
     * Constructor.
     *
     * @param \FootyRoom\Repositories\CommentRepository $commentRepo
     * @param \FootyRoom\App\Comment\CommentingService $commentingService
     * @param \FootyRoom\Core\Comment\CommentPolicy $commentPolicy
     * @param \Illuminate\Contracts\Events\Dispatcher $events
     */
    public function __construct(
        CommentRepository $commentRepo,
        CommentingService $commentingService,
        CommentPolicy $commentPolicy,
        Dispatcher $events
    ) {
        $this->commentRepo = $commentRepo;
        $this->commentPolicy = $commentPolicy;
        $this->commentingService = $commentingService;
        $this->events = $events;
    }

    /**
     * Edit comment.
     *
     * @param \FootyRoom\App\Comment\EditCommentCommand $command
     * @param \FootyRoom\User\User $user
     */
    public function handle(EditCommentCommand $command, User $user)
    {
        // Get original comment.
        $comment = $this->commentRepo->findById($command->commentId);

        if (!$comment) {
            throw new CoreException('This comment does not exist. It may have been removed while you were editing it.');
        }

        // Authorize this edit.
        $this->commentPolicy->canEdit($user, $comment->getAuthor()->getUserId(), $comment->getDiscussionId(), true);
        $this->commentPolicy->canComment($user, true);

        // Check comment for blacklisted words.
        $this->commentingService->checkBlacklistedWords([$command->content]);

        $newContent = $this->commentingService->formatComment($command->content, $command->images);

        $comment->editContent($newContent, $newContent, $user);

        // Save modified comment and a previous revision.
        $this->commentRepo->updateContent($comment->getId(), $comment->getContent(), $comment->getContent());

        foreach ($comment->releaseEvents() as $event) {
            $this->events->dispatch($event);
        }
    }
}