Completed
Pull Request — master (#456)
by Alejandro
14:16
created

CacheFactory   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
eloc 16
dl 0
loc 38
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0

3 Methods

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