1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TraderInteractive\Api; |
4
|
|
|
|
5
|
|
|
use MongoDB; |
6
|
|
|
use Predis; |
7
|
|
|
use Psr\SimpleCache\CacheInterface; |
8
|
|
|
use SubjectivePHP\Psr\SimpleCache\InMemoryCache; |
9
|
|
|
use SubjectivePHP\Psr\SimpleCache\MongoCache; |
10
|
|
|
use SubjectivePHP\Psr\SimpleCache\NullCache; |
11
|
|
|
use SubjectivePHP\Psr\SimpleCache\RedisCache; |
12
|
|
|
|
13
|
|
|
final class CacheFactory |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @param string $name The name of the cache object to make. |
17
|
|
|
* @param array $config Options to use when constructing the cache. |
18
|
|
|
* |
19
|
|
|
* @return CacheInterface |
20
|
|
|
*/ |
21
|
|
|
public static function make(string $name, array $config) : CacheInterface |
22
|
|
|
{ |
23
|
|
|
if ($name === MongoCache::class) { |
24
|
|
|
return self::getMongoCache($config); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
if ($name === RedisCache::class) { |
28
|
|
|
return self::getRedisCache($config); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
if ($name === InMemoryCache::class) { |
32
|
|
|
return new InMemoryCache(); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
if ($name === NullCache::class) { |
36
|
|
|
return new NullCache(); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
throw new \RuntimeException("Cannot create cache instance of '{$name}'"); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
private static function getMongoCache(array $config) : MongoCache |
43
|
|
|
{ |
44
|
|
|
return new MongoCache(self::getMongoCollectionFromConfig($config), new ResponseSerializer()); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
private static function getMongoCollectionFromConfig(array $config) : MongoDB\Collection |
48
|
|
|
{ |
49
|
|
|
$collection = $config['collection']; |
50
|
|
|
if ($collection instanceof MongoDB\Collection) { |
51
|
|
|
return $collection; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$uri = $config['uri']; |
55
|
|
|
$database = $config['database']; |
56
|
|
|
return (new MongoDB\Client($uri))->selectDatabase($database)->selectCollection($collection); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private static function getRedisCache(array $config) : RedisCache |
60
|
|
|
{ |
61
|
|
|
$parameters = $config['parameters'] ?? null; |
62
|
|
|
$options = $config['options'] ?? null; |
63
|
|
|
return new RedisCache(new Predis\Client($parameters, $options)); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|