1 | <?php |
||
2 | |||
3 | namespace Awssat\Visits; |
||
4 | |||
5 | use Illuminate\Database\Eloquent\Model; |
||
6 | use Illuminate\Support\Str; |
||
7 | |||
8 | class Keys |
||
9 | { |
||
10 | public $modelName = false; |
||
11 | public $id; |
||
12 | public $visits; |
||
13 | public $primary = 'id'; |
||
14 | public $instanceOfModel = false; |
||
15 | public $tag; |
||
16 | |||
17 | public function __construct($subject, $tag) |
||
18 | { |
||
19 | $this->modelName = $this->pluralModelName($subject); |
||
20 | $this->primary = (new $subject)->getKeyName(); |
||
21 | $this->tag = $tag; |
||
22 | $this->visits = $this->visits(); |
||
23 | |||
24 | if ($subject instanceof Model) { |
||
25 | $this->instanceOfModel = true; |
||
26 | $this->modelName = $this->modelName($subject); |
||
27 | $this->id = $subject->{$subject->getKeyName()}; |
||
28 | } |
||
29 | } |
||
30 | |||
31 | /** |
||
32 | * Get cache key |
||
33 | */ |
||
34 | public function visits() |
||
35 | { |
||
36 | return (app()->environment('testing') ? 'testing:' : '').$this->modelName."_{$this->tag}"; |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
37 | } |
||
38 | |||
39 | /** |
||
40 | * Get cache key for total values |
||
41 | */ |
||
42 | public function visitsTotal() |
||
43 | { |
||
44 | return "{$this->visits}_total"; |
||
45 | } |
||
46 | |||
47 | /** |
||
48 | * ip key |
||
49 | */ |
||
50 | public function ip($ip) |
||
51 | { |
||
52 | return $this->visits.'_'.Str::snake( |
||
53 | 'recorded_ips:'.($this->instanceOfModel ? "{$this->id}:" : '') . $ip |
||
54 | ); |
||
55 | } |
||
56 | |||
57 | /** |
||
58 | * list cache key |
||
59 | */ |
||
60 | public function cache($limit = '*', $isLow = false, $constraints = []) |
||
61 | { |
||
62 | $key = $this->visits.'_lists'; |
||
63 | |||
64 | if ($limit == '*') { |
||
65 | return "{$key}:*"; |
||
66 | } |
||
67 | |||
68 | //it might not be that unique but it does the job since not many lists |
||
69 | //will be generated to one key. |
||
70 | $constraintsPart = count($constraints) ? ':'.substr(sha1(serialize($constraints)), 0, 7) : ''; |
||
71 | |||
72 | return "{$key}:".($isLow ? 'low' : 'top').$constraintsPart.$limit; |
||
73 | } |
||
74 | |||
75 | /** |
||
76 | * period key |
||
77 | */ |
||
78 | public function period($period) |
||
79 | { |
||
80 | return "{$this->visits}_{$period}"; |
||
81 | } |
||
82 | |||
83 | public function append($relation, $id) |
||
84 | { |
||
85 | $this->visits .= "_{$relation}_{$id}"; |
||
86 | } |
||
87 | |||
88 | public function modelName($subject) |
||
89 | { |
||
90 | return strtolower(Str::singular(class_basename(get_class($subject)))); |
||
91 | } |
||
92 | |||
93 | public function pluralModelName($subject) |
||
94 | { |
||
95 | return strtolower(Str::plural(class_basename(is_string($subject) ? $subject : get_class($subject)))); |
||
96 | } |
||
97 | } |
||
98 |