Passed
Push — master ( f9389a...e0bec9 )
by Mihail
04:05
created

CachePool   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 2
c 1
b 0
f 0
dl 0
loc 26
ccs 6
cts 6
cp 1
rs 10
eloc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
use() 0 13 ?
A hp$0 ➔ use() 0 13 1
A hp$0 ➔ __construct() 0 3 1
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
    /**
26
     * @var CacheItemPoolInterface[] The registry
27
     */
28
    private static $instances = [];
29
30
    /**
31
     * @param string $client     The name of the cache client
32
     * @param array  $parameters [optional] Configuration parameters for the cache client
33
     *
34
     * @return CacheItemPoolInterface
35
     */
36 831
    public static function use(string $client, array $parameters = []): CacheItemPoolInterface
37
    {
38 831
        $ident = md5($client . serialize($parameters));
39
40 831
        if (isset(self::$instances[$ident])) {
41 822
            return self::$instances[$ident];
42
        }
43
44
        return self::$instances[$ident] = new class($client, $parameters) extends CacheItemPool
45
        {
46 9
            public function __construct(string $client, array $parameters)
47
            {
48 9
                $this->client = simple_cache_factory($client, $parameters);
49 9
            }
50
        };
51
    }
52
}
53
54
/**
55
 * Implementation for \Psr\Cache\InvalidArgumentException
56
 *
57
 */
58
class CachePoolException extends Exception implements InvalidArgumentException
59
{
60 560
    public static function from(Exception $e)
61
    {
62 560
        return new self($e->getMessage(), $e->getCode());
63
    }
64
}