CacheFactory   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 15
c 0
b 0
f 0
dl 0
loc 35
rs 10
ccs 17
cts 17
cp 1
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A __invoke() 0 7 1
A buildAdapter() 0 17 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Common\Cache;
6
7
use Closure;
8
use Doctrine\Common\Cache;
9
use Predis\Client as PredisClient;
10
use Psr\Container\ContainerInterface;
11
12
use function extension_loaded;
13
14
class CacheFactory
15
{
16
    private Closure $apcuEnabled;
17
18 5
    public function __construct(?callable $apcuEnabled = null)
19
    {
20 5
        $this->apcuEnabled = Closure::fromCallable($apcuEnabled ?? fn () => extension_loaded('apcu'));
21
    }
22
23 5
    public function __invoke(ContainerInterface $container): Cache\CacheProvider
24
    {
25 5
        $config = $container->get('config');
26 5
        $adapter = $this->buildAdapter($config, $container);
27 5
        $adapter->setNamespace($config['cache']['namespace'] ?? '');
28
29 5
        return $adapter;
30
    }
31
32 5
    private function buildAdapter(array $config, ContainerInterface $container): Cache\CacheProvider
33
    {
34 5
        $isDebug = (bool) ($config['debug'] ?? false);
35 5
        $redisConfig = $config['cache']['redis'] ?? null;
36 5
        $apcuEnabled = ($this->apcuEnabled)();
37
38 5
        if ($isDebug || (! $apcuEnabled && $redisConfig === null)) {
39 2
            return new Cache\ArrayCache();
40
        }
41
42 3
        if ($redisConfig === null) {
43 2
            return new Cache\ApcuCache();
44
        }
45
46
        /** @var PredisClient $predis */
47 1
        $predis = $container->get(RedisFactory::SERVICE_NAME);
48 1
        return new Cache\PredisCache($predis);
49
    }
50
}
51