Passed
Pull Request — master (#365)
by Alejandro
06:55
created

CacheFactory::getAdapter()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 4
nc 3
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
ccs 5
cts 5
cp 1
crap 4
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Common\Factory;
5
6
use Doctrine\Common\Cache;
7
use Interop\Container\ContainerInterface;
8
use Interop\Container\Exception\ContainerException;
9
use Memcached;
10
use Shlinkio\Shlink\Core\Options\AppOptions;
11
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
12
use Zend\ServiceManager\Exception\ServiceNotFoundException;
13
use Zend\ServiceManager\Factory\FactoryInterface;
14
15
use function Functional\contains;
16
use function Shlinkio\Shlink\Common\env;
17
use function sys_get_temp_dir;
18
19
class CacheFactory implements FactoryInterface
20
{
21
    private const VALID_CACHE_ADAPTERS = [
22
        Cache\ApcuCache::class,
23
        Cache\ArrayCache::class,
24
        Cache\FilesystemCache::class,
25
        Cache\PhpFileCache::class,
26
        Cache\MemcachedCache::class,
27
    ];
28
    private const DEFAULT_MEMCACHED_PORT = 11211;
29
30
    /**
31
     * Create an object
32
     *
33
     * @param  ContainerInterface $container
34
     * @param  string $requestedName
35
     * @param  null|array $options
36
     * @return object
37
     * @throws ServiceNotFoundException if unable to resolve the service.
38
     * @throws ServiceNotCreatedException if an exception is raised when
39
     *     creating a service.
40
     * @throws ContainerException if any other error occurs
41
     */
42 6
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
43
    {
44 6
        $appOptions = $container->get(AppOptions::class);
45 6
        $adapter = $this->getAdapter($container);
46 6
        $adapter->setNamespace((string) $appOptions);
47
48 6
        return $adapter;
49
    }
50
51 6
    private function getAdapter(ContainerInterface $container): Cache\CacheProvider
52
    {
53
        // Try to get the adapter from config
54 6
        $config = $container->get('config');
55 6
        if (isset($config['cache']['adapter']) && contains(self::VALID_CACHE_ADAPTERS, $config['cache']['adapter'])) {
56 3
            return $this->resolveCacheAdapter($config['cache']);
57
        }
58
59
        // If the adapter has not been set in config, create one based on environment
60 3
        return env('APP_ENV', 'pro') === 'pro' ? new Cache\ApcuCache() : new Cache\ArrayCache();
61
    }
62
63 3
    private function resolveCacheAdapter(array $cacheConfig): Cache\CacheProvider
64
    {
65 3
        switch ($cacheConfig['adapter']) {
66
            case Cache\ArrayCache::class:
67
            case Cache\ApcuCache::class:
68 1
                return new $cacheConfig['adapter']();
69
            case Cache\FilesystemCache::class:
70
            case Cache\PhpFileCache::class:
71 1
                return new $cacheConfig['adapter']($cacheConfig['options']['dir'] ?? sys_get_temp_dir());
72
            case Cache\MemcachedCache::class:
73 1
                $cache = new Cache\MemcachedCache();
74 1
                $cache->setMemcached($this->buildMemcached($cacheConfig));
75 1
                return $cache;
76
            default:
77
                return new Cache\ArrayCache();
78
        }
79
    }
80
81 1
    private function buildMemcached(array $cacheConfig): Memcached
82
    {
83 1
        $memcached = new Memcached();
84 1
        $servers = $cacheConfig['options']['servers'] ?? [];
85
86 1
        foreach ($servers as $server) {
87 1
            $this->addMemcachedServer($memcached, $server);
88
        }
89
90 1
        return $memcached;
91
    }
92
93 1
    private function addMemcachedServer(Memcached $memcached, array $server): void
94
    {
95 1
        if (! isset($server['host'])) {
96
            return;
97
        }
98 1
        $port = (int) ($server['port'] ?? self::DEFAULT_MEMCACHED_PORT);
99
100 1
        $memcached->addServer($server['host'], $port);
101
    }
102
}
103