Periods::noExpiration()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Awssat\Visits\Traits;
4
5
use Illuminate\Support\Carbon;
6
use Illuminate\Support\Str;
7
use Exception;
8
9
trait Periods
10
{
11
    /**
12
     * Sync periods times
13
     */
14
    protected function periodsSync()
15
    {
16
        foreach ($this->periods as $period) {
17
            $periodKey = $this->keys->period($period);
18
19
            if ($this->noExpiration($periodKey)) {
20
                $expireInSeconds = $this->newExpiration($period);
21
                $this->connection->increment($periodKey.'_total', 0);
22
                $this->connection->increment($periodKey, 0, 0);
23
                $this->connection->setExpiration($periodKey, $expireInSeconds);
24
                $this->connection->setExpiration($periodKey.'_total', $expireInSeconds);
25
            }
26
        }
27
    }
28
29
    protected function noExpiration($periodKey)
30
    {
31
        return $this->connection->timeLeft($periodKey) == -1 || ! $this->connection->exists($periodKey);
32
    }
33
34
    protected function newExpiration($period)
35
    {
36
        try {
37
            $periodCarbon = $this->xHoursPeriod($period) ?? Carbon::now()->{'endOf' . Str::studly($period)}();
38
        } catch (Exception $e) {
39
            throw new Exception("Wrong period: `{$period}`! please update config/visits.php file.");
40
        }
41
42
        return $periodCarbon->diffInSeconds() + 1;
43
    }
44
45
    /**
46
     * @param $period
47
     * @return mixed
48
     */
49
    protected function xHoursPeriod($period)
50
    {
51
        preg_match('/([\d]+)\s?([\w]+)/', $period, $match);
52
        return isset($match[2]) && isset($match[1]) && $match[2] == 'hours' && $match[1] < 12
53
                ? Carbon::now()->endOfxHours((int) $match[1]) 
54
                : null;
55
    }
56
}
57