ViewCounter.php
1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?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;
}
}
}
}