PrerenderWhenCommentedOnMatch.php 1.48 KB
<?php

namespace FootyRoom\Core\Prerender;

use FootyRoom\PrerenderJob;
use FootyRoom\Http\Match\MatchSlug;
use Illuminate\Contracts\Bus\Dispatcher;
use FootyRoom\Core\Comment\CommentPosted;
use Illuminate\Contracts\Cache\Factory as CacheFactory;

class PrerenderWhenCommentedOnMatch
{
    /**
     * @var \Illuminate\Contracts\Cache\Repository
     */
    private $cache;

    /** @var \Illuminate\Contracts\Bus\Dispatcher */
    private $dispatcher;

    public function __construct(CacheFactory $cache, Dispatcher $dispatcher)
    {
        $this->cache = $cache->store('common');
        $this->dispatcher = $dispatcher;
    }

    /**
     * Dispatch job for prerendering
     *
     * @param \FootyRoom\Core\Comment\CommentPosted $event
     */
    public function handle(CommentPosted $event)
    {
        if ($event->commentable->getCommentableType() == 'match') {
            $url = route('matchReview', [
                'id' => $event->commentable->getId(),
                'slug' => MatchSlug::fromTeams($event->commentable->getHomeTeam()->getName(), $event->commentable->getAwayTeam()->getName()),
            ]);

            // We don't want to prerender on every comment but debounce for 10 minutes
            $debounceKey = 'prerender-debounce-match:'.$event->commentable->getId();

            if (!$this->cache->has($debounceKey)) {
                $this->cache->put($debounceKey, true, 10);
                $this->dispatcher->dispatch(new PrerenderJob($url, true));
            }
        }
    }
}