Completed
Push — master ( ee9f14...51c1c1 )
by
unknown
14s queued 10s
created

CacheFactory::getMongoCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace TraderInteractive\Api;
4
5
use MongoDB;
6
use Psr\SimpleCache\CacheInterface;
7
use SubjectivePHP\Psr\SimpleCache\InMemoryCache;
8
use SubjectivePHP\Psr\SimpleCache\MongoCache;
9
use SubjectivePHP\Psr\SimpleCache\NullCache;
10
11
final class CacheFactory
12
{
13
    /**
14
     * @param string $name   The name of the cache object to make.
15
     * @param array  $config Options to use when constructing the cache.
16
     *
17
     * @return CacheInterface
18
     */
19
    public static function make(string $name, array $config) : CacheInterface
20
    {
21
        if ($name === MongoCache::class) {
22
            return self::getMongoCache($config);
23
        }
24
25
        if ($name === InMemoryCache::class) {
26
            return new InMemoryCache();
27
        }
28
29
        if ($name === NullCache::class) {
30
            return new NullCache();
31
        }
32
33
        throw new \RuntimeException("Cannot create cache instance of '{$name}'");
34
    }
35
36
    private static function getMongoCache(array $config) : MongoCache
37
    {
38
        return new MongoCache(self::getMongoCollectionFromConfig($config), new ResponseSerializer());
39
    }
40
41
    private static function getMongoCollectionFromConfig(array $config) : MongoDB\Collection
42
    {
43
        $collection = $config['collection'];
44
        if ($collection instanceof MongoDB\Collection) {
45
            return $collection;
46
        }
47
48
        $uri = $config['uri'];
49
        $database = $config['database'];
50
        return (new MongoDB\Client($uri))->selectDatabase($database)->selectCollection($collection);
51
    }
52
}
53