Completed
Push — master ( 68b000...ef386c )
by bader
04:04
created

Periods::xHoursPeriod()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
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