Passed
Pull Request — main (#3)
by Michael
03:09
created

InteractsWithCache::cacheClue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
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;
0 ignored issues
show
Bug introduced by
The constant MichaelRubel\AutoBinder\...ctsWithCache::CACHE_KEY was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
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(
0 ignored issues
show
Bug introduced by
It seems like cache()->get($this->cacheClue()) can also be of type Illuminate\Contracts\Cache\Repository; however, parameter $value of collect() does only seem to accept Illuminate\Contracts\Support\Arrayable, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

43
        collect(/** @scrutinizer ignore-type */ cache()->get($this->cacheClue()))->each(
Loading history...
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