Passed
Push — master ( 671601...c4a055 )
by Andreas
16:47
created

midcom_services_cache_module::prepare_backend()   B

Complexity

Conditions 9
Paths 24

Size

Total Lines 35
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 22.8922

Importance

Changes 0
Metric Value
cc 9
eloc 27
c 0
b 0
f 0
nc 24
nop 2
dl 0
loc 35
ccs 12
cts 27
cp 0.4444
crap 22.8922
rs 8.0555
1
<?php
2
/**
3
 * @package midcom.services
4
 * @author The Midgard Project, http://www.midgard-project.org
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
use Doctrine\Common\Cache;
10
use Doctrine\Common\Cache\CacheProvider;
11
12
/**
13
 * This is the base class for the MidCOM cache modules. It provides a basic infrastructure
14
 * for building your own caching service, providing hooks for initialization.
15
 *
16
 * It provides convenience methods to start up the cache module, for example for the creation
17
 * of a cache backend instance. There is no specific initialization done during startup, to
18
 * allow the modules to do their own magic during startup (it is difficult to generalize such
19
 * stuff).
20
 *
21
 * @package midcom.services
22
 */
23
abstract class midcom_services_cache_module
24
{
25
    /**
26
     * A list of all backends created by _create_backend(). They will be automatically
27
     * shut down when the module shuts down. They are indexed by their name.
28
     *
29
     * @var Doctrine\Common\Cache\CacheProvider[]
30
     */
31
    protected $_backends = [];
32
33
    /**
34
     * The cache key prefix.
35
     *
36
     * @var string
37
     */
38
    private $_prefix;
39
40
    /**
41
     * Cache backend instance.
42
     *
43
     * @var Doctrine\Common\Cache\CacheProvider
44
     */
45
    protected $backend;
46
47
    /**
48
     * Initialize the module. This will initialize the class configuration
49
     * and call the corresponding event handler.
50
     */
51 1
    public function __construct()
52
    {
53 1
        $this->_prefix = get_class($this) . $_SERVER['SERVER_NAME'];
54 1
        $this->backend = new Cache\VoidCache();
55 1
    }
56
57
    /**
58
     * Creates an instance of the handler described by the configuration passed to
59
     * the function.
60
     *
61
     * The configuration array must include the configuration parameters driver and
62
     * directory, as outlined in the midcom_services_cache_backend class documentation.
63
     *
64
     * All backends will be collected in the $_backends array, indexed by their name.
65
     *
66
     * Any duplicate instantiation will be intercepted, throwing a critical error.
67
     *
68
     * @param string $name The name of the backend, must be unique throughout the system.
69
     * @param array $config The configuration of the backend to create. It must contain
70
     *     the key 'driver', which indicates which backend to use.
71
     */
72 1
    protected function _create_backend($name, array $config) : CacheProvider
73
    {
74 1
        $name = $this->_prefix . $name;
75
76 1
        if (array_key_exists($name, $this->_backends)) {
77
            throw new midcom_error("Cannot create backend driver instance {$name}: A backend with this name does already exist.");
78
        }
79
80 1
        if (!array_key_exists('driver', $config)) {
81
            throw new midcom_error("Cannot create backend driver instance {$name}: The driver class is not specified in the configuration.");
82
        }
83
84 1
        if (is_string($config['driver'])) {
85 1
            $backend = $this->prepare_backend($config, $name);
86
        } else {
87
            $backend = $config['driver'];
88
        }
89 1
        $backend->setNamespace($name);
90
91 1
        $this->_backends[$name] = $backend;
92
93 1
        return $backend;
94
    }
95
96 1
    private function prepare_backend(array $config, string $name) : CacheProvider
97
    {
98 1
        $directory = midcom::get()->getCacheDir();
99 1
        if (!empty($config['directory'])) {
100 1
            $directory .= '/' . $config['directory'];
101
        }
102
103 1
        switch ($config['driver']) {
104 1
            case 'apc':
105
                $backend = new Cache\ApcuCache();
106
                break;
107 1
            case 'memcached':
108 1
                if ($memcached = midcom_services_cache_module_memcache::prepare_memcached($config)) {
109 1
                    $backend = new Cache\MemcachedCache();
110 1
                    $backend->setMemcached($memcached);
111 1
                    break;
112
                }
113
                debug_add("memcache: Failed to connect. Falling back to filecache", MIDCOM_LOG_ERROR);
114
                // fall-through
115
            case 'dba':
116
            case 'flatfile':
117
                $backend = new Cache\FilesystemCache($directory . '/' . $name);
118
                break;
119
            case 'sqlite':
120
                $sqlite = new SQLite3("{$directory}/{$name}.db");
121
                $table = str_replace(['.', '-'], '_', $name);
122
                $backend = new Cache\SQLite3Cache($sqlite, $table);
123
                break;
124
            case 'null':
125
            default:
126
                $backend = new Cache\VoidCache();
127
                break;
128
        }
129
130 1
        return new Cache\ChainCache([new Cache\ArrayCache, $backend]);
131
    }
132
133
    /**
134
     * Invalidate the cache completely, dropping all entries. The default implementation will
135
     * drop all entries from all registered cache backends using CacheProvider::flushAll().
136
     * Override this function if this behavior doesn't suit your needs.
137
     */
138
    public function invalidate_all()
139
    {
140
        foreach ($this->_backends as $name => $backend) {
141
            debug_add("Invalidating cache backend {$name}...", MIDCOM_LOG_INFO);
142
            $backend->flushAll();
143
        }
144
    }
145
146
    /**
147
     * Invalidate all cache objects related to the given GUID.
148
     *
149
     * @param string $guid The GUID that has to be invalidated.
150
     * @param object $object The object that has to be invalidated (if available).
151
     */
152
    abstract public function invalidate($guid, $object = null);
153
}
154