-
-
Notifications
You must be signed in to change notification settings - Fork 269
/
CacheFactory.php
95 lines (78 loc) · 2.49 KB
/
CacheFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
declare(strict_types=1);
namespace DoctrineModule\Service;
use Doctrine\Common\Cache;
use Doctrine\Common\Cache\CacheProvider;
use DoctrineModule\Cache\LaminasStorageCache;
use DoctrineModule\Options\Cache as CacheOptions;
use Psr\Container\ContainerInterface;
use RuntimeException;
use function get_class;
use function is_string;
use function sprintf;
/**
* Cache ServiceManager factory
*/
final class CacheFactory extends AbstractFactory
{
/**
* {@inheritDoc}
*
* @return Cache\Cache
*
* @throws RuntimeException
*/
public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null)
{
$options = $this->getOptions($container, 'cache');
if (! $options instanceof CacheOptions) {
throw new RuntimeException(sprintf(
'Invalid options received, expected %s, got %s.',
CacheOptions::class,
get_class($options)
));
}
$class = $options->getClass();
if (! $class) {
throw new RuntimeException('Cache must have a class name to instantiate');
}
$instance = $options->getInstance();
if (is_string($instance) && $container->has($instance)) {
$instance = $container->get($instance);
}
if ($container->has($class)) {
$cache = $container->get($class);
} else {
switch ($class) {
case Cache\FilesystemCache::class:
$cache = new $class($options->getDirectory());
break;
case LaminasStorageCache::class:
case Cache\PredisCache::class:
$cache = new $class($instance);
break;
default:
$cache = new $class();
break;
}
}
if ($cache instanceof Cache\MemcacheCache) {
$cache->setMemcache($instance);
} elseif ($cache instanceof Cache\MemcachedCache) {
$cache->setMemcached($instance);
} elseif ($cache instanceof Cache\RedisCache) {
$cache->setRedis($instance);
}
if ($cache instanceof CacheProvider) {
$namespace = $options->getNamespace();
if ($namespace) {
$cache->setNamespace($namespace);
}
}
return $cache;
}
public function getOptionsClass(): string
{
return CacheOptions::class;
}
}