Passed
Push — master ( 156190...17a9a7 )
by bader
02:48
created

Keys::append()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
rs 10
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->visits . '_' .
59
            snake_case("recorded_ips:" . ($this->instanceOfModel ? "{$this->id}:" : '') . $ip);
60
    }
61
62
63
    /**
64
     * @param $limit
65
     * @param $isLow
66
     * @return string
67
     */
68
    public function cache($limit = '*', $isLow = false)
69
    {
70
        $key = $this->visits . "_lists";
71
72
        if ($limit == '*') {
73
            return "{$key}:*";
74
        }
75
76
        return "{$key}:" . ($isLow ? "low" : "top") . "{$limit}";
77
    }
78
79
    /**
80
     * @param $period
81
     * @return string
82
     */
83
    public function period($period)
84
    {
85
        return "{$this->visits}_{$period}";
86
    }
87
88
    /**
89
     * @param $relation
90
     * @param $id
91
     */
92
    public function append($relation, $id)
93
    {
94
        $this->visits .= "_{$relation}_{$id}";
95
    }
96
}
97