1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace awssat\Visits\Traits; |
4
|
|
|
|
5
|
|
|
use Carbon\Carbon; |
6
|
|
|
use Exception; |
7
|
|
|
|
8
|
|
|
trait Periods |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Sync periods times |
12
|
|
|
*/ |
13
|
|
|
protected function periodsSync() |
14
|
|
|
{ |
15
|
|
|
foreach ($this->periods as $period) { |
16
|
|
|
$periodKey = $this->keys->period($period); |
17
|
|
|
|
18
|
|
|
if ($this->noExpiration($periodKey)) { |
19
|
|
|
$expireInSeconds = $this->newExpiration($period); |
20
|
|
|
$this->redis->incrby($periodKey . '_total', 0); |
21
|
|
|
$this->redis->zincrby($periodKey, 0, 0); |
22
|
|
|
$this->redis->expire($periodKey, $expireInSeconds); |
23
|
|
|
$this->redis->expire($periodKey . '_total', $expireInSeconds); |
24
|
|
|
} |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param $periodKey |
30
|
|
|
* @return bool |
31
|
|
|
*/ |
32
|
|
|
protected function noExpiration($periodKey) |
33
|
|
|
{ |
34
|
|
|
return $this->redis->ttl($periodKey) == -1 || !$this->redis->exists($periodKey); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param $period |
39
|
|
|
* @return int |
40
|
|
|
* @throws Exception |
41
|
|
|
*/ |
42
|
|
|
protected function newExpiration($period) |
43
|
|
|
{ |
44
|
|
|
try { |
45
|
|
|
$periodCarbon = $this->xHoursPeriod($period) ?? |
46
|
|
|
Carbon::now()->{'endOf' . studly_case($period)}(); |
47
|
|
|
} catch (Exception $exception) { |
48
|
|
|
throw new Exception('Wrong period : ' . $period . |
49
|
|
|
' please update your visits.php config'); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return ($periodCarbon->timestamp - Carbon::now()->timestamp) + 1; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param $period |
57
|
|
|
* @return mixed |
58
|
|
|
*/ |
59
|
|
|
protected function xHoursPeriod($period) |
60
|
|
|
{ |
61
|
|
|
return collect(range(1, 12))->map(function ($hour) { |
62
|
|
|
return ['method' => $hour . 'hours', 'hours' => $hour]; |
63
|
|
|
})->where('method', $period) |
64
|
|
|
->pluck('hours') |
65
|
|
|
->map(function ($hours) { |
66
|
|
|
return Carbon::now()->endOfxHours($hours); |
67
|
|
|
}) |
68
|
|
|
->first(); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|