CachePoolException::from()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 1
c 2
b 0
f 1
dl 0
loc 3
ccs 0
cts 0
cp 0
rs 10
nc 1
nop 1
cc 1
crap 2
1
<?php
2
3
namespace Koded\Caching;
4
5
use Exception;
6
use Psr\Cache\{CacheItemPoolInterface, InvalidArgumentException};
7
8
/**
9
 * CachePool creates instances of CacheItemPoolInterface classes.
10
 * The instances are created only once.
11
 *
12
 * Production ready:
13
 *
14
 *  - Redis, with redis extension
15
 *  - Redis, with Predis library
16
 *  - Memcached
17
 *
18
 * Additional for development:
19
 *  - File
20
 *  - Memory
21
 *
22
 */
23
final class CachePool
24
{
25
    /** @var CacheItemPoolInterface[] The registry */
26
    private static array $instances = [];
27
28
    /**
29
     * @param string $client     The name of the cache client
30
     * @param array  $parameters [optional] Configuration parameters for the cache client
31
     * @return CacheItemPoolInterface
32
     */
33
    public static function use(string $client, array $parameters = []): CacheItemPoolInterface
34
    {
35
        $ident = \md5($client . \serialize($parameters));
36 831
        if (isset(self::$instances[$ident])) {
37
            return self::$instances[$ident];
38 831
        }
39
        return self::$instances[$ident] = new class($client, $parameters) extends CacheItemPool
40 831
        {
41 822
            public function __construct(string $client, array $parameters)
42
            {
43
                $this->client = simple_cache_factory($client, $parameters);
44
            }
45
        };
46 9
    }
47
}
48 9
49 9
/**
50
 * Implementation for \Psr\Cache\InvalidArgumentException
51
 *
52
 */
53
class CachePoolException extends Exception implements InvalidArgumentException
54
{
55
    public static function from(Exception $e): static
56
    {
57
        return new static($e->getMessage(), $e->getCode());
58
    }
59
}
60