Test Failed
Push — 1.0.0-dev ( 069ccf...edefc3 )
by nguereza
02:24
created

DatabaseCache   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 194
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 1
Metric Value
eloc 42
dl 0
loc 194
rs 10
c 1
b 1
f 1
wmc 19

13 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 setCacheInstance() 0 3 1
A getCacheInstance() 0 2 1
A getCacheContent() 0 11 3
A getCacheKey() 0 2 1
A setPropertiesValues() 0 6 2
A saveCacheContent() 0 11 3
A setCacheInstanceFromSuperInstanceIfNull() 0 7 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 cache instance
41
         * @var object
42
         */
43
        private $cacheInstance = 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 getCacheInstance() {
117
            return $this->cacheInstance;
118
        }
119
120
        /**
121
         * Set the cache instance
122
         * @param object CacheInterface $cache the cache object
123
         * @return object Database
124
         */
125
        public function setCacheInstance($cache) {
126
            $this->cacheInstance = $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
        /**
153
         * Get the cache content for this query
154
         * @see Database::query
155
         *      
156
         * @return mixed
157
         */
158
        public function getCacheContent() {
159
            //set some attributes values
160
            $this->setPropertiesValues();
161
            if(! $this->isSelectQuery || ! $this->dbCacheStatus){
162
                $this->logger->info('The cache is not enabled for this query or is not a SELECT query'); 
163
                return null;
164
            }
165
            $this->setCacheInstanceFromSuperInstanceIfNull();
166
            $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
167
            $cacheKey = $this->getCacheKey();
168
            return $this->cacheInstance->get($cacheKey);
169
        }
170
171
        /**
172
         * Save the result of query into cache
173
         * @param string $key    the cache key
174
         * @param mixed $result the query result to save
175
         * @param int $expire the cache TTL
176
         *
177
         * @return boolean|null the status of the operation
178
         */
179
        public function saveCacheContent($result) {
180
            //set some attributes values
181
            $this->setPropertiesValues();
182
            if(! $this->isSelectQuery || ! $this->dbCacheStatus){
183
                //just return true
184
                return null;
185
            }
186
            $this->setCacheInstanceFromSuperInstanceIfNull();
187
            $cacheKey = $this->getCacheKey();
188
            $this->logger->info('Save the result for query [' . $this->query . '] into cache for future use');
189
            return $this->cacheInstance->set($cacheKey, $result, $this->cacheTtl);
190
        }
191
192
        /**
193
         * Set the cache instance using the super global instance if the current instance is null 
194
         * and the cache feature is enabled.
195
         */
196
        protected function setCacheInstanceFromSuperInstanceIfNull() {
197
            if (!is_object($this->cacheInstance)) {
198
                //can not call method with reference in argument
199
                //like $this->setCacheInstance(& get_instance()->cache);
200
                //use temporary variable
201
                $instance = & get_instance()->cache;
202
                $this->cacheInstance = $instance;
203
            }
204
        }
205
206
        /**
207
         * Set some properties values to use later
208
         */
209
        protected function setPropertiesValues() {
210
            //If is the SELECT query
211
            $this->isSelectQuery = stristr($this->query, 'SELECT') !== false;
212
213
             //if can use cache feature for this query
214
            $this->dbCacheStatus = get_config('cache_enable', false) && $this->cacheTtl > 0;
215
        }
216
        
217
        /**
218
         * Return the cache key for the current query
219
         * @see Database::query
220
         * 
221
         *  @return string
222
         */
223
        protected function getCacheKey() {
224
            return md5($this->query . $this->returnAsList . $this->returnAsArray);
225
        }
226
227
}
228