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