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 InteractsWithCache |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Get the clue to access the cache. |
15
|
|
|
* |
16
|
|
|
* @return string |
17
|
|
|
*/ |
18
|
16 |
|
public function cacheClue(): string |
19
|
|
|
{ |
20
|
16 |
|
return static::CACHE_KEY . $this->classFolder; |
|
|
|
|
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Check if the caching is enabled. |
25
|
|
|
* |
26
|
|
|
* @return bool |
27
|
|
|
* @throws InvalidArgumentException |
28
|
|
|
*/ |
29
|
17 |
|
protected function isCachingEnabled(): bool |
30
|
|
|
{ |
31
|
17 |
|
return $this->caching && cache()->has($this->cacheClue()); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Use the bindings from the cache. |
36
|
|
|
* |
37
|
|
|
* @return void |
38
|
|
|
* @throws ContainerExceptionInterface |
39
|
|
|
* @throws NotFoundExceptionInterface |
40
|
|
|
*/ |
41
|
|
|
protected function fromCache(): void |
42
|
|
|
{ |
43
|
|
|
collect(cache()->get($this->cacheClue()))->each( |
|
|
|
|
44
|
|
|
fn ($concrete, $interface) => app()->{$this->bindingType}($interface, $concrete) |
45
|
|
|
); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Cache the binding. |
50
|
|
|
* |
51
|
|
|
* @param string $interface |
52
|
|
|
* @param \Closure|string $concrete |
53
|
|
|
* |
54
|
|
|
* @return void |
55
|
|
|
* @throws ContainerExceptionInterface |
56
|
|
|
* @throws NotFoundExceptionInterface |
57
|
|
|
*/ |
58
|
15 |
|
protected function cacheBindingFor(string $interface, \Closure|string $concrete): void |
59
|
|
|
{ |
60
|
15 |
|
$clue = $this->cacheClue(); |
61
|
|
|
|
62
|
15 |
|
$cache = cache()->get($clue); |
63
|
|
|
|
64
|
15 |
|
$cache[$interface] = $concrete; |
65
|
|
|
|
66
|
15 |
|
cache()->put($clue, $cache); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|