Test Failed
Push — develop ( fe93c2...a526c9 )
by nguereza
05:50
created

ApcCache::get()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 3
eloc 14
c 1
b 1
f 0
nc 3
nop 1
dl 0
loc 17
rs 9.7998
1
<?php
2
    defined('ROOT_PATH') or exit('Access denied');
3
    /**
4
     * TNH Framework
5
     *
6
     * A simple PHP framework using HMVC architecture
7
     *
8
     * This content is released under the MIT License (MIT)
9
     *
10
     * Copyright (c) 2017 TNH Framework
11
     *
12
     * Permission is hereby granted, free of charge, to any person obtaining a copy
13
     * of this software and associated documentation files (the "Software"), to deal
14
     * in the Software without restriction, including without limitation the rights
15
     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
     * copies of the Software, and to permit persons to whom the Software is
17
     * furnished to do so, subject to the following conditions:
18
     *
19
     * The above copyright notice and this permission notice shall be included in all
20
     * copies or substantial portions of the Software.
21
     *
22
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
     * SOFTWARE.
29
     */
30
	
31
    class ApcCache extends BaseClass implements CacheInterface {
32
33
        /**
34
         * Construct new ApcCache instance
35
         */
36
	public function __construct() {
37
            parent::__construct();
38
            if (!$this->isSupported()) {
39
                show_error('The cache for APC[u] driver is not available. Check if APC[u] extension is loaded and enabled.');
40
            }
41
        }
42
43
        /**
44
         * This is used to get the cache data using the key
45
         * 
46
         * @param  string $key the key to identify the cache data
47
         * 
48
         * @return mixed      the cache data if exists else return false
49
         */
50
        public function get($key) {
51
            $this->logger->debug('Getting cache data for key [' . $key . ']');
52
            $success = false;
53
            $data = apc_fetch($key, $success);
54
            if ($success === false) {
55
                $this->logger->info('No cache found for the key [' . $key . '], return false');
56
                return false;
57
            } 
58
            $cacheInfo = $this->getCacheInfo($key);
59
            $expire = time();
60
            if ($cacheInfo) {
61
                $expire = $cacheInfo['creation_time'] + $cacheInfo['ttl'];
62
            }
63
            $this->logger->info('The cache not yet expire, now return the cache'
64
                                . ' data for key [' . $key . '], the cache will' 
65
                                . ' expire at [' . date('Y-m-d H:i:s', $expire) . ']');
66
            return $data;
67
        }
68
69
70
        /**
71
         * Save data to the cache
72
         * 
73
         * @param string  $key  the key to identify this cache data
74
         * @param mixed  $data the cache data to be saved
75
         * @param integer $ttl  the cache life time
76
         * 
77
         * @return boolean true if success otherwise will return false
78
         */
79
        public function set($key, $data, $ttl = 0) {
80
            $expire = time() + $ttl;
81
            $this->logger->debug('Setting cache data for key [' . $key . '], time to live [' . $ttl . '], '
82
                                 . 'expire at [' . date('Y-m-d H:i:s', $expire) . ']');
83
            $result = apc_store($key, $data, $ttl);
84
            if ($result === false) {
85
                $this->logger->error('Can not save cache data for the key [' . $key . '], return false');
86
                return false;
87
            }
88
            $this->logger->info('Cache data saved for the key [' . $key . ']');
89
            return true;
90
        }
91
92
93
        /**
94
         * Delete the cache data for given key
95
         * 
96
         * @param  string $key the key for cache to be deleted
97
         * 
98
         * @return boolean      true if the cache is deleted, false if can't delete 
99
         * the cache or the cache with the given key not exist
100
         */
101
        public function delete($key) {
102
            $this->logger->debug('Deleting of cache data for key [' . $key . ']');
103
            $cacheInfo = $this->getCacheInfo($key);
104
            if ($cacheInfo === false) {
105
                $this->logger->info('This cache data does not exists skipping');
106
                return false;
107
            } 
108
            $this->logger->info('Found cache data for the key [' . $key . '] remove it');
109
            return apc_delete($key) === true;
110
        }
111
		
112
        /**
113
         * Get the cache information for given key
114
         * 
115
         * @param  string $key the key for cache to get the information for
116
         * 
117
         * @return boolean|array    the cache information. The associative array and must contains the following information:
118
         * 'mtime' => creation time of the cache (Unix timestamp),
119
         * 'expire' => expiration time of the cache (Unix timestamp),
120
         * 'ttl' => the time to live of the cache in second
121
         */
122
        public function getInfo($key) {
123
            $this->logger->debug('Getting of cache info for key [' . $key . ']');
124
            $cacheInfos = $this->getCacheInfo($key);
125
            if ($cacheInfos) {
126
                return array(
127
                            'mtime'  => $cacheInfos['creation_time'],
128
                            'expire' => $cacheInfos['creation_time'] + $cacheInfos['ttl'],
129
                            'ttl'    => $cacheInfos['ttl']
130
                           );
131
            } 
132
            $this->logger->info('This cache does not exists skipping');
133
            return false;
134
        }
135
136
137
        /**
138
         * Used to delete expired cache data
139
         * @see  CacheInterface::deleteExpiredCache
140
         */
141
        public function deleteExpiredCache() {
142
            //for APC[u] is done automatically
143
            return true;
144
        }
145
146
        /**
147
         * Remove all cache data
148
         * @see  CacheInterface::clean
149
         */
150
        public function clean() {
151
            $this->logger->debug('Deleting of all cache data');
152
            $cacheInfos = apc_cache_info('user');
153
            if (empty($cacheInfos['cache_list'])) {
154
                $this->logger->info('No cache data were found skipping');
155
                return false;
156
            } 
157
            $this->logger->info('Found [' . count($cacheInfos) . '] cache data to remove');
158
            return apc_clear_cache('user');
159
        }
160
		
161
		
162
        /**
163
         * Check whether the cache feature for the handle is supported
164
         *
165
         * @return bool
166
         */
167
        public function isSupported() {
168
            return (extension_loaded('apc') || extension_loaded('apcu')) && ini_get('apc.enabled');
169
        }
170
		
171
        /**
172
         * Return the array of cache information
173
         *
174
         * @param string $key the cache key to get the cache information 
175
         * 
176
         * @return boolean|array
177
         */
178
        private function getCacheInfo($key) {
179
            $caches = apc_cache_info('user');
180
            if (!empty($caches['cache_list'])) {
181
                $cacheLists = $caches['cache_list'];
182
                foreach ($cacheLists as $info) {
183
                    if (isset($info['info']) && $info['info'] === $key) {
184
                        return $info;
185
                    }
186
                }
187
            }
188
            return false;
189
        }
190
    }
191