Completed
Push — v5 ( c89db4...8b8972 )
by Georges
04:26
created

CacheManager::getNamespacePath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 2
eloc 2
nc 2
nop 0
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\Cache\ExtendedCacheItemPoolInterface;
18
use phpFastCache\Core\DriverAbstract;
19
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
20
use CouchbaseCluster;
21
22
/**
23
 * Class CacheManager
24
 * @package phpFastCache
25
 *
26
 * @method static DriverAbstract Apc() Apc($config = []) Return a driver "apc" instance
27
 * @method static DriverAbstract Cookie() Cookie($config = []) Return a driver "cookie" instance
28
 * @method static DriverAbstract Files() Files($config = []) Return a driver "files" instance
29
 * @method static DriverAbstract Memcache() Memcache($config = []) Return a driver "memcache" instance
30
 * @method static DriverAbstract Memcached() Memcached($config = []) Return a driver "memcached" instance
31
 * @method static DriverAbstract Predis() Predis($config = []) Return a driver "predis" instance
32
 * @method static DriverAbstract Redis() Redis($config = []) Return a driver "redis" instance
33
 * @method static DriverAbstract Sqlite() Sqlite($config = []) Return a driver "sqlite" instance
34
 * @method static DriverAbstract Ssdb() Ssdb($config = []) Return a driver "ssdb" instance
35
 * @method static DriverAbstract Wincache() Wincache($config = []) Return a driver "wincache" instance
36
 * @method static DriverAbstract Xcache() Xcache($config = []) Return a driver "xcache" instance
37
 *
38
 */
39
class CacheManager
40
{
41
    /**
42
     * @var int
43
     */
44
    public static $ReadHits = 0;
45
46
    /**
47
     * @var int
48
     */
49
    public static $WriteHits = 0;
50
51
    /**
52
     * @var array
53
     */
54
    protected static $config = [
55
      'securityKey' => 'auto',// The securityKey that will be used to create sub-directory
56
      'htaccess' => true,// Auto-generate .htaccess if tit is missing
57
      'default_chmod' => 0777, // 0777 recommended
58
      'path' => '',// if not set will be the value of sys_get_temp_dir()
59
      'fallback' => false, //Fall back when old driver is not support
60
      "limited_memory_each_object" => 4096, // maximum size (bytes) of object store in memory
61
      "compress_data" => false, // compress stored data, if the backend supports it
62
    ];
63
64
    /**
65
     * @var string
66
     */
67
    protected static $namespacePath;
68
69
    /**
70
     * @var array
71
     */
72
    protected static $instances = [];
73
74
    /**
75
     * @param string $driver
76
     * @param array $config
77
     * @return ExtendedCacheItemPoolInterface
78
     */
79
    public static function getInstance($driver = 'auto', $config = [])
80
    {
81
        static $badPracticeOmeter = [];
82
83
        /**
84
         * @todo: Standardize a method for driver name
85
         */
86
        $driver = self::standardizeDriverName($driver);
87
        $config = array_merge(self::$config, $config);
88
        if (!$driver || $driver === 'Auto') {
89
            $driver = self::getAutoClass($config);
90
        }
91
92
        $instance = crc32($driver . serialize($config));
93
        if (!isset(self::$instances[ $instance ])) {
94
            $badPracticeOmeter[$driver] = 1;
95
            $class = self::getNamespacePath() . $driver . '\Driver';
96
            try{
97
                self::$instances[ $instance ] = new $class($config);
98
            }catch(phpFastCacheDriverCheckException $e){
99
                $fallback = self::standardizeDriverName($config['fallback']);
100
                if($fallback && $fallback !== $driver){
101
                    $class = self::getNamespacePath() . $fallback . '\Driver';
102
                    self::$instances[ $instance ] = new $class($config);
103
                    trigger_error(sprintf('The "%s" driver is unavailable at the moment, the fallback driver "%s" has been used instead.', $driver, $fallback), E_USER_WARNING);
104
                }else{
105
                    throw new phpFastCacheDriverCheckException($e->getMessage(), $e->getCode(), $e);
106
                }
107
            }
108
        } else if(++$badPracticeOmeter[$driver] >= 5){
109
           trigger_error('[' . $driver . '] Calling many times CacheManager::getInstance() for already instanced drivers is a bad practice and have a significant impact on performances.
110
           See https://github.com/PHPSocialNetwork/phpfastcache/wiki/[V5]-Why-calling-getInstance%28%29-each-time-is-a-bad-practice-%3F');
111
        }
112
113
        return self::$instances[ $instance ];
114
    }
115
116
    /**
117
     * @param $config
118
     * @return string
119
     * @throws phpFastCacheDriverCheckException
120
     */
121
    public static function getAutoClass($config = [])
122
    {
123
        static $autoDriver;
124
125
        if ($autoDriver === null) {
126
            foreach (self::getStaticSystemDrivers() as $driver) {
127
                try {
128
                    self::getInstance($driver, $config);
129
                    $autoDriver = $driver;
130
                } catch (phpFastCacheDriverCheckException $e) {
131
                    continue;
132
                }
133
            }
134
        }
135
136
        return $autoDriver;
137
    }
138
139
    /**
140
     * @param string $name
141
     * @param array $arguments
142
     * @return \Psr\Cache\CacheItemPoolInterface
143
     */
144
    public static function __callStatic($name, $arguments)
145
    {
146
        $options = (array_key_exists(0, $arguments) && is_array($arguments) ? $arguments[ 0 ] : []);
147
148
        return self::getInstance($name, $options);
149
    }
150
151
    /**
152
     * @return bool
153
     */
154
    public static function clearInstances()
155
    {
156
        foreach (self::$instances as &$instance) {
157
            unset($instance);
158
        }
159
160
        gc_collect_cycles();
161
        return !count(self::$instances);
162
    }
163
164
    /**
165
     * @return string
166
     */
167
    public static function getNamespacePath()
168
    {
169
        return self::$namespacePath ?: __NAMESPACE__ . '\Drivers\\';
170
    }
171
172
    /**
173
     * @param string $path
174
     */
175
    public static function setNamespacePath($path)
176
    {
177
        self::$namespacePath = $path;
178
    }
179
180
    /**
181
     * @param $name
182
     * @param string $value
183
     * @deprecated Method "setup" is deprecated and will be removed in 5.1. Use method "setDefaultConfig" instead.
184
     */
185
    public static function setup($name, $value = '')
186
    {
187
        trigger_error('Method "setup" is deprecated and will be removed in 5.1. Use method "setDefaultConfig" instead.');
188
        self::setDefaultConfig($name, $value);
189
    }
190
191
    /**
192
     * @param $name string|array
193
     * @param mixed $value
194
     */
195
    public static function setDefaultConfig($name, $value = null)
196
    {
197
        if (is_array($name)) {
198
            self::$config = array_merge(self::$config, $name);
199
        } else if (is_string($name)){
200
            self::$config[ $name ] = $value;
201
        }else{
202
            throw new \InvalidArgumentException('Invalid variable type: $name');
203
        }
204
    }
205
206
    /**
207
     * @return array
208
     */
209
    public static function getDefaultConfig()
210
    {
211
        return self::$config;
212
    }
213
214
    /**
215
     * @return array
216
     */
217
    public static function getStaticSystemDrivers()
218
    {
219
        return [
220
          'Sqlite',
221
          'Files',
222
          'Apc',
223
          'Apcu',
224
          'Memcache',
225
          'Memcached',
226
          'Couchbase',
227
          'Mongodb',
228
          'Predis',
229
          'Redis',
230
          'Ssdb',
231
          'Leveldb',
232
          'Wincache',
233
          'Xcache',
234
          'Devnull',
235
        ];
236
    }
237
238
    /**
239
     * @return array
240
     */
241
    public static function getStaticAllDrivers()
242
    {
243
        return array_merge(self::getStaticSystemDrivers(), [
244
            'Devtrue',
245
            'Devfalse',
246
            'Cookie',
247
        ]);
248
    }
249
250
    /**
251
     * @param string $driverName
252
     * @return string
253
     */
254
    public static function standardizeDriverName($driverName)
255
    {
256
        return ucfirst(strtolower(trim($driverName)));
257
    }
258
}
259