Passed
Push — master ( 446d1f...4a5808 )
by Stephen
08:36
created

AbstractViewModel::setTTL()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Sfneal\ViewModels;
4
5
use Illuminate\Http\Response;
6
use Illuminate\Support\Facades\View;
7
use RuntimeException;
8
use Sfneal\Helpers\Redis\RedisCache;
9
use Spatie\ViewModels\ViewModel;
10
11
abstract class AbstractViewModel extends ViewModel
12
{
13
    /**
14
     * @var int Time to live
15
     */
16
    public $ttl = null;
17
18
    /**
19
     * @var string Use manually declare redis_key (warning: can cause issues with caching)
20
     */
21
    public $redis_key = null;
22
23
    /**
24
     * View Directory Prefix.
25
     */
26
    public $prefix;
27
28
    /**
29
     * @var null View name
30
     */
31
    public $view = null;
32
33
    /**
34
     * Render the View.
35
     *
36
     * @return string
37
     */
38
    private function __render(): string
39
    {
40
        return View::make($this->view, $this->toArray())->render();
41
    }
42
43
    /**
44
     * Retrieve the authenticated user's ID from the session.
45
     *
46
     *  - avoid executing database query
47
     *
48
     * @return int
49
     */
50
    private function userId(): int
51
    {
52
        try {
53
            // Find the 'login_web' session key that holds the authenticated user_id value
54
            // If there's no key containing 'login_web' the user is not logged in
55
            $session_key = collect(request()->session()->all())->keys()->filter(function ($key) {
56
                return is_string($key) && inString($key, 'login_web');
57
            })->first();
58
        } catch (RuntimeException $runtimeException) {
59
            // request and/or session is not set (called from a job)
60
            $session_key = 0;
61
        }
62
63
        // Get the $session_key if it's not null
64
        return ! empty($session_key) ? session()->get($session_key) : 0;
65
    }
66
67
    /**
68
     * Retrieve a unique redis key for caching the view.
69
     *
70
     * @return string
71
     */
72
    private function redisViewKey(): string
73
    {
74
        return 'views'.
75
            ':'.$this->view.
76
            '#'.$this->userId().
77
            '#'.(isset($this->redis_key) ? $this->redis_key : request()->fullUrl());
78
    }
79
80
    /**
81
     * Set an override Redis Key.
82
     *
83
     * @param string $redis_key
84
     * @return $this
85
     */
86
    public function setRedisKey(string $redis_key): self
87
    {
88
        $this->redis_key = $redis_key;
89
90
        return $this;
91
    }
92
93
    /**
94
     * Retrieve/render the ViewModel from/to the application cache.
95
     *
96
     * @param string|null $view
97
     * @param int|null $ttl
98
     * @return string
99
     */
100
    public function render(string $view = null, int $ttl = null): string
101
    {
102
        // Set $view if it is not null
103
        if ($view) {
104
            $this->view = $view;
0 ignored issues
show
Documentation Bug introduced by
It seems like $view of type string is incompatible with the declared type null of property $view.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
105
        }
106
107
        // Cache the View if it doesn't exist
108
        return RedisCache::remember($this->redisViewKey(), $this->getTTL($ttl), function () {
109
            return $this->__render();
110
        });
111
    }
112
113
    /**
114
     * Render the ViewModel without storing or retrieving from the Cache.
115
     *
116
     * @param string|null $view
117
     * @return Response|string|mixed
118
     */
119
    public function renderNoCache(string $view = null)
120
    {
121
        // Set $view if it is not null
122
        if ($view) {
123
            $this->view = $view;
0 ignored issues
show
Documentation Bug introduced by
It seems like $view of type string is incompatible with the declared type null of property $view.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
124
        }
125
126
        return $this->__render();
127
    }
128
129
    /**
130
     * Invalidate the View Cache for this ViewModel.
131
     *
132
     * @return $this
133
     */
134
    public function invalidateCache(): self
135
    {
136
        RedisCache::delete('views:'.$this->view);
137
138
        return $this;
139
    }
140
141
    /**
142
     * Return a concatenated route or view name by using the PREFIX const.
143
     *
144
     * @param string $string
145
     * @return $this
146
     */
147
    public function viewWithPrefix(string $string): self
148
    {
149
        $this->view = $this->prefix.$string;
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->prefix . $string of type string is incompatible with the declared type null of property $view.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
150
151
        return $this;
152
    }
153
154
    /**
155
     * Extend a view name.
156
     *
157
     * @param string $string
158
     * @return $this
159
     */
160
    public function viewExtend(string $string): self
161
    {
162
        $this->view .= $string;
163
164
        return $this;
165
    }
166
167
    /**
168
     * Retrieve the time to live for the cached values
169
     *  - 1. passed $ttl parameter
170
     *  - 2. initialized $this->ttl property
171
     *  - 3. application default cache ttl.
172
     *
173
     * @param int|null $ttl
174
     * @return int
175
     */
176
    private function getTTL(int $ttl = null): int
177
    {
178
        return intval($ttl ?? $this->ttl ?? env('REDIS_KEY_EXPIRATION'));
179
    }
180
181
    /**
182
     * Set the $ttl property during runtime
183
     *
184
     * @param int $ttl
185
     * @return $this
186
     */
187
    public function setTTL(int $ttl): self
188
    {
189
        $this->ttl = $ttl;
190
        return $this;
191
    }
192
}
193