-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathTemplateLoader.php
97 lines (77 loc) · 2.24 KB
/
TemplateLoader.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
namespace LaravelEnso\Tables\Services;
use Illuminate\Cache\TaggableStore;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
use LaravelEnso\Tables\Contracts\DynamicTemplate;
use LaravelEnso\Tables\Contracts\Table;
class TemplateLoader
{
private Template $template;
private array $cache;
public function __construct(private Table $table)
{
}
public function handle()
{
$this->load();
return $this->template;
}
private function load()
{
$this->template = $this->fromCache() ?? $this->new();
if ($this->shouldCache()) {
$this->cache()->put($this->cacheKey(), $this->template->toArray());
}
$this->template->buildNonCacheable();
}
private function fromCache()
{
if (!$this->cache()->has($this->cacheKey())) {
return;
}
$this->cache = $this->cache()->get($this->cacheKey());
return (new Template($this->table))
->load($this->cache['template'], $this->cache['meta']);
}
private function new()
{
return (new Template($this->table))->buildCacheable();
}
private function shouldCache()
{
if (isset($this->cache)) {
return false;
}
$type = $this->template->get(
'templateCache',
Config::get('enso.tables.cache.template')
);
switch ($type) {
case 'never':
return false;
case 'always':
return true;
default:
return app()->environment($type);
}
}
private function cacheKey(): string
{
$configPrefix = Config::get('enso.tables.cache.prefix');
$prefix = $this->table instanceof DynamicTemplate
? "{$this->table->cachePrefix()}:"
: null;
return Str::of($this->table->templatePath())
->replace(['/', '.'], [' ', ' '])
->slug()
->prepend("{$configPrefix}:{$prefix}");
}
private function cache()
{
return Cache::getStore() instanceof TaggableStore
? Cache::tags(Config::get('enso.tables.cache.tag'))
: Cache::store();
}
}