ViewCounter.php 1.58 KB
<?php

namespace FootyRoom\App;

use FootyRoom\Queries\MatchQuery;
use FootyRoom\Queries\PostQuery;
use Illuminate\Contracts\Cache\Factory as CacheFactory;

class ViewCounter
{
    const STEP = 150;

    /**
     * @var \FootyRoom\Queries\PostQuery
     */
    protected $postQuery;

    /**
     * @var \Illuminate\Contracts\Cache\Factory
     */
    protected $cache;

    /**
     * Constructor.
     *
     * @param \Illuminate\Contracts\Cache\Factory $cache
     */
    public function __construct(CacheFactory $cache)
    {
        $this->cache = $cache->store('shared');
    }

    /**
     * Increments page view count for a given post.
     *
     * @param int $postId
     * @param int $step
     */
    public function increment($objectRef, $step = self::STEP)
    {
        $cacheKey = "views:$objectRef";

        $count = $this->cache->increment($cacheKey, 1);

        if ($count === false) {
            if ($this->cache->add($cacheKey, 1, 0) !== true) {
                $count = $this->cache->increment($cacheKey, 1);
            } else {
                $count = 1;
            }
        }

        if (($count % $step) === 0) {
            list($objectType, $objectId) = explode(':', $objectRef);

            switch ($objectType) {
                case 'match':
                    app(MatchQuery::class)->incrementViewCount($objectId, $step);
                    break;

                case 'post':
                    app(PostQuery::class)->incrementViewCount($objectId, $step);
                    break;

                default:
                    break;
            }
        }
    }
}