Completed
Push — V6 ( cc1a0a...3a8b38 )
by Georges
04:31
created

CacheManager::getInstances()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
/**
3
 *
4
 * This file is part of phpFastCache.
5
 *
6
 * @license MIT License (MIT)
7
 *
8
 * For full copyright and license information, please see the docs/CREDITS.txt file.
9
 *
10
 * @author Khoa Bui (khoaofgod)  <[email protected]> http://www.phpfastcache.com
11
 * @author Georges.L (Geolim4)  <[email protected]>
12
 *
13
 */
14
15
namespace phpFastCache;
16
17
use phpFastCache\Core\Pool\ExtendedCacheItemPoolInterface;
18
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
19
20
/**
21
 * Class CacheManager
22
 * @package phpFastCache
23
 *
24
 * @method static ExtendedCacheItemPoolInterface Apc() Apc($config = []) Return a driver "apc" instance
25
 * @method static ExtendedCacheItemPoolInterface Apcu() Apcu($config = []) Return a driver "apcu" instance
26
 * @method static ExtendedCacheItemPoolInterface Cookie() Cookie($config = []) Return a driver "cookie" instance
27
 * @method static ExtendedCacheItemPoolInterface Couchbase() Couchbase($config = []) Return a driver "couchbase" instance
28
 * @method static ExtendedCacheItemPoolInterface Files() Files($config = []) Return a driver "files" instance
29
 * @method static ExtendedCacheItemPoolInterface Leveldb() Leveldb($config = []) Return a driver "leveldb" instance
30
 * @method static ExtendedCacheItemPoolInterface Memcache() Memcache($config = []) Return a driver "memcache" instance
31
 * @method static ExtendedCacheItemPoolInterface Memcached() Memcached($config = []) Return a driver "memcached" instance
32
 * @method static ExtendedCacheItemPoolInterface Mongodb() Mongodb($config = []) Return a driver "mongodb" instance
33
 * @method static ExtendedCacheItemPoolInterface Predis() Predis($config = []) Return a driver "predis" instance
34
 * @method static ExtendedCacheItemPoolInterface Redis() Redis($config = []) Return a driver "redis" instance
35
 * @method static ExtendedCacheItemPoolInterface Sqlite() Sqlite($config = []) Return a driver "sqlite" instance
36
 * @method static ExtendedCacheItemPoolInterface Ssdb() Ssdb($config = []) Return a driver "ssdb" instance
37
 * @method static ExtendedCacheItemPoolInterface Wincache() Wincache($config = []) Return a driver "wincache" instance
38
 * @method static ExtendedCacheItemPoolInterface Xcache() Xcache($config = []) Return a driver "xcache" instance
39
 * @method static ExtendedCacheItemPoolInterface Zenddisk() Zenddisk($config = []) Return a driver "zend disk cache" instance
40
 * @method static ExtendedCacheItemPoolInterface Zendshm() Zendshm($config = []) Return a driver "zend memory cache" instance
41
 *
42
 */
43
class CacheManager
44
{
45
    /**
46
     * @var int
47
     */
48
    public static $ReadHits = 0;
49
50
    /**
51
     * @var int
52
     */
53
    public static $WriteHits = 0;
54
55
    /**
56
     * @var ExtendedCacheItemPoolInterface[]
57
     */
58
    protected static $config = [
59
      'itemDetailedDate' => false,// Specify if the item must provide detailed creation/modification dates
60
      'defaultTtl' => 900,// Default time-to-live in second
61
      'securityKey' => 'auto',// The securityKey that will be used to create sub-directory
62
      'htaccess' => true,// Auto-generate .htaccess if tit is missing
63
      'default_chmod' => 0777, // 0777 recommended
64
      'path' => '',// if not set will be the value of sys_get_temp_dir()
65
      'fallback' => false, //Fall back when old driver is not support
66
      'limited_memory_each_object' => 4096, // maximum size (bytes) of object store in memory
67
      'compress_data' => false, // compress stored data, if the backend supports it
68
    ];
69
70
    /**
71
     * @var string
72
     */
73
    protected static $namespacePath;
74
75
    /**
76
     * @var array
77
     */
78
    protected static $instances = [];
79
80
    /**
81
     * @param string $driver
82
     * @param array $config
83
     * @return ExtendedCacheItemPoolInterface
84
     * @throws phpFastCacheDriverCheckException
85
     */
86
    public static function getInstance($driver = 'auto', $config = [])
87
    {
88
        static $badPracticeOmeter = [];
89
90
        /**
91
         * @todo: Standardize a method for driver name
92
         */
93
        $driver = self::standardizeDriverName($driver);
94
        $config = array_merge(self::$config, $config);
95
        if (!$driver || $driver === 'Auto') {
96
            $driver = self::getAutoClass($config);
97
        }
98
99
        $instance = crc32($driver . serialize($config));
100
        if (!isset(self::$instances[ $instance ])) {
101
            $badPracticeOmeter[$driver] = 1;
102
            $class = self::getNamespacePath() . $driver . '\Driver';
103
            try{
104
                self::$instances[ $instance ] = new $class($config);
105
            }catch(phpFastCacheDriverCheckException $e){
106
                $fallback = self::standardizeDriverName($config['fallback']);
107
                if($fallback && $fallback !== $driver){
108
                    $class = self::getNamespacePath() . $fallback . '\Driver';
109
                    self::$instances[ $instance ] = new $class($config);
110
                    trigger_error(sprintf('The "%s" driver is unavailable at the moment, the fallback driver "%s" has been used instead.', $driver, $fallback), E_USER_WARNING);
111
                }else{
112
                    throw new phpFastCacheDriverCheckException($e->getMessage(), $e->getCode(), $e);
113
                }
114
            }
115
        } else if(++$badPracticeOmeter[$driver] >= 5){
116
           trigger_error('[' . $driver . '] Calling many times CacheManager::getInstance() for already instanced drivers is a bad practice and have a significant impact on performances.
117
           See https://github.com/PHPSocialNetwork/phpfastcache/wiki/[V5]-Why-calling-getInstance%28%29-each-time-is-a-bad-practice-%3F');
118
        }
119
120
        return self::$instances[ $instance ];
121
    }
122
123
    /**
124
     * This method is intended for internal
125
     * use only and should not be used for
126
     * any external development use the
127
     * getInstances() method instead
128
     *
129
     * @internal
130
     * @return ExtendedCacheItemPoolInterface[]
131
     */
132
    public static function getInstances()
133
    {
134
        return self::$instances;
135
    }
136
137
    /**
138
     * This method is intended for internal
139
     * use only and should not be used for
140
     * any external development use the
141
     * getInstances() method instead
142
     *
143
     * @internal
144
     * @return ExtendedCacheItemPoolInterface[]
145
     */
146
    public static function &getInternalInstances()
147
    {
148
        return self::$instances;
149
    }
150
151
    /**
152
     * @param $config
153
     * @return string
154
     * @throws phpFastCacheDriverCheckException
155
     */
156
    public static function getAutoClass($config = [])
157
    {
158
        static $autoDriver;
159
160
        if ($autoDriver === null) {
161
            foreach (self::getStaticSystemDrivers() as $driver) {
162
                try {
163
                    self::getInstance($driver, $config);
164
                    $autoDriver = $driver;
165
                } catch (phpFastCacheDriverCheckException $e) {
166
                    continue;
167
                }
168
            }
169
        }
170
171
        return $autoDriver;
172
    }
173
174
    /**
175
     * @param string $name
176
     * @param array $arguments
177
     * @return \Psr\Cache\CacheItemPoolInterface
178
     */
179
    public static function __callStatic($name, $arguments)
180
    {
181
        $options = (array_key_exists(0, $arguments) && is_array($arguments) ? $arguments[ 0 ] : []);
182
183
        return self::getInstance($name, $options);
184
    }
185
186
    /**
187
     * @return bool
188
     */
189
    public static function clearInstances()
190
    {
191
        self::$instances = [];
192
193
        gc_collect_cycles();
194
        return !count(self::$instances);
195
    }
196
197
    /**
198
     * @return string
199
     */
200
    public static function getNamespacePath()
201
    {
202
        return self::$namespacePath ?: __NAMESPACE__ . '\Drivers\\';
203
    }
204
205
    /**
206
     * @param string $path
207
     */
208
    public static function setNamespacePath($path)
209
    {
210
        self::$namespacePath = $path;
211
    }
212
213
    /**
214
     * @param $name
215
     * @param string $value
216
     * @deprecated Method "setup" is deprecated and will be removed in V6. Use method "setDefaultConfig" instead.
217
     * @throws \InvalidArgumentException
218
     */
219
    public static function setup($name, $value = '')
220
    {
221
        trigger_error('Method "setup" is deprecated and will be removed in V6 Use method "setDefaultConfig" instead.');
222
        self::setDefaultConfig($name, $value);
223
    }
224
225
    /**
226
     * @param $name string|array
227
     * @param mixed $value
228
     * @throws \InvalidArgumentException
229
     */
230
    public static function setDefaultConfig($name, $value = null)
231
    {
232
        if (is_array($name)) {
233
            self::$config = array_merge(self::$config, $name);
0 ignored issues
show
Documentation Bug introduced by
It seems like array_merge(self::$config, $name) of type array is incompatible with the declared type array<integer,object<php...acheItemPoolInterface>> of property $config.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
234
        } else if (is_string($name)){
235
            self::$config[ $name ] = $value;
236
        }else{
237
            throw new \InvalidArgumentException('Invalid variable type: $name');
238
        }
239
    }
240
241
    /**
242
     * @return array
243
     */
244
    public static function getDefaultConfig()
245
    {
246
        return self::$config;
247
    }
248
249
    /**
250
     * @return array
251
     */
252
    public static function getStaticSystemDrivers()
253
    {
254
        return [
255
          'Sqlite',
256
          'Files',
257
          'Apc',
258
          'Apcu',
259
          'Memcache',
260
          'Memcached',
261
          'Couchbase',
262
          'Mongodb',
263
          'Predis',
264
          'Redis',
265
          'Ssdb',
266
          'Leveldb',
267
          'Wincache',
268
          'Xcache',
269
          'Devnull',
270
        ];
271
    }
272
273
    /**
274
     * @return array
275
     */
276
    public static function getStaticAllDrivers()
277
    {
278
        return array_merge(self::getStaticSystemDrivers(), [
279
            'Devtrue',
280
            'Devfalse',
281
            'Cookie',
282
        ]);
283
    }
284
285
    /**
286
     * @param string $driverName
287
     * @return string
288
     */
289
    public static function standardizeDriverName($driverName)
290
    {
291
        return ucfirst(strtolower(trim($driverName)));
292
    }
293
}
294