Completed
Push — master ( f8882e...156190 )
by bader
03:45
created

Keys::__construct()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 4
nop 2
dl 0
loc 13
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace awssat\Visits;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
class Keys
8
{
9
    public $prefix;
10
    public $testing = '';
11
    public $modelName = false;
12
    public $id;
13
    public $visits;
14
    public $primary = 'id';
15
    public $instanceOfModel = false;
16
    public $tag;
17
18
    /**
19
     * Keys constructor.
20
     * @param $subject
21
     * @param $tag
22
     */
23
    public function __construct($subject, $tag)
24
    {
25
        $this->modelName = strtolower(str_plural(class_basename(is_string($subject) ? $subject : get_class($subject))));
26
        $this->prefix = config('visits.redis_keys_prefix');
27
        $this->testing = app()->environment('testing') ? 'testing:' : '';
28
        $this->primary = (new $subject)->getKeyName();
29
        $this->tag = $tag;
30
        $this->visits = $this->visits($subject);
31
32
        if ($subject instanceof Model) {
33
            $this->instanceOfModel = true;
34
            $this->modelName = strtolower(str_singular(class_basename(get_class($subject))));
35
            $this->id = $subject->{$subject->getKeyName()};
36
        }
37
    }
38
39
    /**
40
     * Get cache key
41
     *
42
     * @param $key
43
     * @return string
44
     */
45
    public function visits($key)
46
    {
47
        return "{$this->prefix}:$this->testing" .
48
            strtolower(str_plural(class_basename(is_string($key) ? $key : get_class($key))))
49
            . "_{$this->tag}";
50
    }
51
52
    /**
53
     * @param $ip
54
     * @return string
55
     */
56
    public function ip($ip)
57
    {
58
        return "{$this->prefix}:$this->testing" . snake_case("recorded_ips:" . ($this->instanceOfModel ? "{$this->modelName}_{$this->tag}_{$this->id}:" : '') . $ip);
59
    }
60
61
62
    /**
63
     * @param $limit
64
     * @param $isLow
65
     * @return string
66
     */
67
    public function cache($limit = '*', $isLow = false)
68
    {
69
        $key = "{$this->prefix}:$this->testing" . "lists";
70
        if ($limit == '*') {
71
            return "{$key}:*";
72
        }
73
        return "{$key}:" . ($isLow ? "low" : "top") . "{$limit}_{$this->modelName}";
74
    }
75
76
    /**
77
     * @param $period
78
     * @return string
79
     */
80
    public function period($period)
81
    {
82
        return "{$this->visits}_{$period}";
83
    }
84
}
85