Passed
Push — master ( 120ad6...d2d121 )
by bader
07:57
created

Periods::newExpiration()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 15
nc 5
nop 1
dl 0
loc 20
rs 9.4555
c 0
b 0
f 0
1
<?php
2
3
namespace awssat\Visits\Traits;
4
5
use Carbon\Carbon;
6
7
trait Periods
8
{
9
    /**
10
     * Sync periods times
11
     */
12
    protected function periodsSync()
13
    {
14
        foreach ($this->periods as $period) {
15
            $periodKey = $this->keys->period($period);
16
17
            if ($this->noExpiration($periodKey)) {
18
                $expireInSeconds = $this->newExpiration($period);
19
                $this->redis->incrby($periodKey . '_total', 0);
20
                $this->redis->zincrby($periodKey, 0, 0);
21
                $this->redis->expire($periodKey, $expireInSeconds);
22
                $this->redis->expire($periodKey . '_total', $expireInSeconds);
23
            }
24
        }
25
    }
26
27
    /**
28
     * @param $periodKey
29
     * @return bool
30
     */
31
    protected function noExpiration($periodKey)
32
    {
33
        return $this->redis->ttl($periodKey) == -1 || !$this->redis->exists($periodKey);
34
    }
35
36
    /**
37
     * @param $period
38
     * @return int
39
     */
40
    protected function newExpiration($period)
41
    {
42
        $expireInSeconds = 0;
43
44
        switch ($period) {
45
            case 'day':
46
                $expireInSeconds = Carbon::now()->endOfDay()->timestamp - Carbon::now()->timestamp;
47
                break;
48
            case 'week':
49
                $expireInSeconds = Carbon::now()->endOfWeek()->timestamp - Carbon::now()->timestamp;
50
                break;
51
            case 'month':
52
                $expireInSeconds = Carbon::now()->endOfMonth()->timestamp - Carbon::now()->timestamp;
53
                break;
54
            case 'year':
55
                $expireInSeconds = Carbon::now()->endOfYear()->timestamp - Carbon::now()->timestamp;
56
                break;
57
        }
58
59
        return $expireInSeconds + 1;
60
    }
61
}
62