Test Failed
Push — 1.0.0-dev ( c68446...90e1c2 )
by nguereza
02:35
created

DatabaseCache   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 201
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
eloc 44
c 2
b 1
f 1
dl 0
loc 201
rs 10
wmc 19

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A setReturnAsArray() 0 3 1
A setQuery() 0 3 1
A setCacheTtl() 0 3 1
A setReturnType() 0 3 1
A getQuery() 0 2 1
A getCacheKey() 0 2 1
A setPropertiesValues() 0 6 2
A setCacheFromSuperInstanceIfNull() 0 7 2
A setCache() 0 3 1
A getCache() 0 2 1
A getCacheContent() 0 11 2
A canUseCache() 0 2 2
A saveCacheContent() 0 11 2
1
<?php
2
    defined('ROOT_PATH') || 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 DatabaseCache extends BaseClass {
32
	
33
        /**
34
         * The cache time to live in second. 0 means no need to use the cache feature
35
         * @var int
36
         */
37
        private $cacheTtl = 0;
38
	
39
        /**
40
         * The CacheInterface instance
41
         * @var object
42
         */
43
        private $cache = null;
44
45
        /**
46
         * The SQL query statment to get or save the result into cache
47
         * @var string
48
         */
49
        private $query = null;
50
51
        /**
52
         * If the current query is the SELECT query
53
         * @var boolean
54
         */
55
        private $isSelectQuery = false;
56
57
        /**
58
         * The status of the database cache
59
         * @var boolean
60
         */
61
        private $dbCacheStatus = false;
62
63
        /**
64
         * Indicate if we need return result as list 
65
         * @var boolean
66
         */
67
        private $returnAsList = true;
68
     
69
     
70
        /**
71
         * Indicate if we need return result as array or not
72
         * @var boolean
73
         */
74
        private $returnAsArray = true;
75
     
76
77
        /**
78
         * Construct new instance
79
         */
80
        public function __construct() {
81
            parent::__construct();
82
        }
83
84
        /**
85
         * Return the current query SQL string
86
         * @return string
87
         */
88
        public function getQuery() {
89
            return $this->query;
90
        }
91
        
92
        /**
93
         * Set the query SQL string
94
         * @param string $query the SQL query to set
95
         * @return object DatabaseQueryRunner
96
         */
97
        public function setQuery($query) {
98
            $this->query = $query;
99
            return $this;
100
        }
101
102
        /**
103
         * Set database cache time to live
104
         * @param integer $ttl the cache time to live in second
105
         * @return object        the current Database instance
106
         */
107
        public function setCacheTtl($ttl = 0) {
108
            $this->cacheTtl = $ttl;
109
            return $this;
110
        }
111
112
        /**
113
         * Return the cache instance
114
         * @return object CacheInterface
115
         */
116
        public function getCache() {
117
            return $this->cache;
118
        }
119
120
        /**
121
         * Set the cache instance
122
         * @param object CacheInterface $cache the cache object
123
         * @return object Database
124
         */
125
        public function setCache($cache) {
126
            $this->cache = $cache;
127
            return $this;
128
        }
129
130
131
        /**
132
         * Set the query return type as list or not
133
         * @param boolean $returnType
134
         * @return object the current instance
135
         */
136
        public function setReturnType($returnType) {
137
            $this->returnAsList = $returnType;
138
            return $this;
139
        }
140
        
141
        /**
142
         * Set the return as array or not
143
         * @param boolean $status the status if true will return as array
144
         * @return object the current instance
145
         */
146
        public function setReturnAsArray($status = true) {
147
            $this->returnAsArray = $status;
148
            return $this;
149
        }
150
    	
151
        /**
152
         * Get the cache content for this query
153
         * @see Database::query
154
         *      
155
         * @return mixed
156
         */
157
        public function getCacheContent() {
158
            //set some attributes values
159
            $this->setPropertiesValues();
160
            if (! $this->canUseCache()) {
161
                $this->logger->info('The cache is not enabled for this query or is not a SELECT query'); 
162
                return null;
163
            }
164
            $this->setCacheFromSuperInstanceIfNull();
165
            $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
166
            $cacheKey = $this->getCacheKey();
167
            return $this->cache->get($cacheKey);
168
        }
169
170
        /**
171
         * Save the result of query into cache
172
         * @param string $key    the cache key
173
         * @param mixed $result the query result to save
174
         * @param int $expire the cache TTL
175
         *
176
         * @return boolean|null the status of the operation
177
         */
178
        public function saveCacheContent($result) {
179
            //set some attributes values
180
            $this->setPropertiesValues();
181
            if (! $this->canUseCache()) {
182
                $this->logger->info('The cache is not enabled for this query or is not a SELECT query'); 
183
                return null;
184
            }
185
            $this->setCacheFromSuperInstanceIfNull();
186
            $cacheKey = $this->getCacheKey();
187
            $this->logger->info('Save the result for query [' . $this->query . '] into cache for future use');
188
            return $this->cache->set($cacheKey, $result, $this->cacheTtl);
189
        }
190
191
        /**
192
         * Set the cache instance using the super global instance if the current instance is null 
193
         * and the cache feature is enabled.
194
         */
195
        protected function setCacheFromSuperInstanceIfNull() {
196
            if (!is_object($this->cache)) {
197
                //can not call method with reference in argument
198
                //like $this->setCache(& get_instance()->cache);
199
                //use temporary variable
200
                $instance = & get_instance()->cache;
201
                $this->cache = $instance;
202
            }
203
        }
204
205
        /**
206
         * Set some properties values to use later
207
         */
208
        protected function setPropertiesValues() {
209
            //If is the SELECT query
210
            $this->isSelectQuery = stristr($this->query, 'SELECT') !== false;
211
212
             //if can use cache feature for this query
213
            $this->dbCacheStatus = get_config('cache_enable', false) && $this->cacheTtl > 0;
214
        }
215
        
216
        /**
217
         * Return the cache key for the current query
218
         * @see Database::query
219
         * 
220
         *  @return string
221
         */
222
        protected function getCacheKey() {
223
            return md5($this->query . $this->returnAsList . $this->returnAsArray);
224
        }
225
226
        /**
227
         * Check whether can use cache feature for the current query
228
         * @return boolean
229
         */
230
        protected function canUseCache() {
231
            return $this->isSelectQuery && $this->dbCacheStatus;
232
        }
233
    }
234