1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace MichaelRubel\AutoBinder\Traits; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
use Psr\Container\ContainerExceptionInterface; |
9
|
|
|
use Psr\Container\NotFoundExceptionInterface; |
10
|
|
|
use Psr\SimpleCache\InvalidArgumentException; |
11
|
|
|
|
12
|
|
|
trait CachesBindings |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Determines if the caching is enabled. |
16
|
|
|
* |
17
|
|
|
* @var bool |
18
|
|
|
*/ |
19
|
|
|
public bool $caching = true; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Disables the caching. |
23
|
|
|
* |
24
|
|
|
* @return static |
25
|
|
|
*/ |
26
|
1 |
|
public function withoutCaching(): static |
27
|
|
|
{ |
28
|
1 |
|
$this->caching = false; |
29
|
|
|
|
30
|
1 |
|
return $this; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Get the clue to access the cache. |
35
|
|
|
* |
36
|
|
|
* @return string |
37
|
|
|
*/ |
38
|
21 |
|
public function cacheClue(): string |
39
|
|
|
{ |
40
|
21 |
|
return static::CACHE_KEY . $this->classFolder; |
|
|
|
|
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Check if the caching is enabled. |
45
|
|
|
* |
46
|
|
|
* @return bool |
47
|
|
|
*/ |
48
|
23 |
|
protected function cacheEnabled(): bool |
49
|
|
|
{ |
50
|
23 |
|
return isset($this->caching) && $this->caching && ! app()->isLocal(); |
|
|
|
|
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Check if the caching is enabled. |
55
|
|
|
* |
56
|
|
|
* @return bool |
57
|
|
|
* @throws InvalidArgumentException |
58
|
|
|
*/ |
59
|
23 |
|
protected function hasCache(): bool |
60
|
|
|
{ |
61
|
23 |
|
return $this->cacheEnabled() && cache()->has($this->cacheClue()); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Use the bindings from the cache. |
66
|
|
|
* |
67
|
|
|
* @return void |
68
|
|
|
* @throws ContainerExceptionInterface |
69
|
|
|
* @throws NotFoundExceptionInterface |
70
|
|
|
*/ |
71
|
3 |
|
protected function fromCache(): void |
72
|
|
|
{ |
73
|
3 |
|
collect(cache()->get($this->cacheClue()))->each( |
|
|
|
|
74
|
3 |
|
fn ($concrete, $interface) => app()->{$this->bindingType}($interface, $concrete) |
75
|
|
|
); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Cache the binding. |
80
|
|
|
* |
81
|
|
|
* @param string $interface |
82
|
|
|
* @param Closure|string $concrete |
83
|
|
|
* |
84
|
|
|
* @return void |
85
|
|
|
* @throws ContainerExceptionInterface |
86
|
|
|
* @throws NotFoundExceptionInterface |
87
|
|
|
*/ |
88
|
20 |
|
protected function cacheBindingFor(string $interface, Closure|string $concrete): void |
89
|
|
|
{ |
90
|
20 |
|
$clue = $this->cacheClue(); |
91
|
|
|
|
92
|
20 |
|
$cache = cache()->get($clue); |
93
|
|
|
|
94
|
20 |
|
$cache[$interface] = $concrete; |
95
|
|
|
|
96
|
20 |
|
cache()->put($clue, $cache); |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
|