Apc::stats()   F
last analyzed

Complexity

Conditions 14
Paths 342

Size

Total Lines 128
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 14
eloc 59
c 1
b 0
f 0
nc 342
nop 0
dl 0
loc 128
rs 3.7522

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Koch Framework
5
 * Jens-André Koch © 2005 - onwards.
6
 *
7
 * This file is part of "Koch Framework".
8
 *
9
 * License: GNU/GPL v2 or any later version, see LICENSE file.
10
 *
11
 * This program is free software; you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation; either version 2 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23
 */
24
25
namespace Koch\Cache\Adapter;
26
27
use Koch\Cache\AbstractCache;
28
use Koch\Cache\CacheInterface;
29
use Koch\Functions\Functions;
30
31
/**
32
 * Koch Framework - Cache Handler for APC (Alternative PHP Cache).
33
 *
34
 * APC is a) an opcache and b) a memory based cache.
35
 *
36
 * Use this class only on PHP versions below PHP 5.5.0.
37
 *
38
 * As of PHP 5.5.0 using APC is no longer required, because
39
 * PHP ships an Opcode Cache (formerly Zend Optimizer+) by default.
40
 * For userland caching APCu is in the making (APC User Cache).
41
 *
42
 * @link http://de3.php.net/manual/de/ref.apc.php
43
 */
44
class Apc extends AbstractCache implements CacheInterface
45
{
46
    /**
47
     * Constructor.
48
     *
49
     * @param array $options
50
     */
51
    public function __construct($options = [])
52
    {
53
        if (extension_loaded('apc') === false) {
54
            throw new \Koch\Exception\Exception(
55
                'The PHP extension APC (Alternative PHP Cache) is not loaded. You may enable it in "php.ini"!'
56
            );
57
        }
58
59
        $enabled = ini_get('apc.enabled');
60
        if (PHP_SAPI === 'cli') {
61
            $enabled = $enabled && (bool) ini_get('apc.enable_cli');
62
        }
63
64
        if ($enabled === false) {
65
            throw new \Koch\Exception\Exception(
66
                'The PHP extension APC (Alternative PHP Cache) is not loaded.' .
67
                "You may enable it with 'apc.enabled=1' and 'apc.enable_cli=1'!"
68
            );
69
        }
70
71
        parent::__construct($options);
72
    }
73
74
    /**
75
     * Read a key from the cache.
76
     *
77
     * @param string $key Identifier for the data
78
     *
79
     * @return bool True if the data was successfully fetched from the cache, false on failure
80
     */
81
    public function fetch($key)
82
    {
83
        return apc_fetch($key);
84
    }
85
86
    /**
87
     * Stores data by key into cache.
88
     *
89
     * @param string $key       Identifier for the data
90
     * @param string $data      Data to be cached
91
     * @param int    $ttl       How long to cache the data, in minutes.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $ttl not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
92
     * @param bool   $overwrite If overwrite true, key will be overwritten.
93
     *
94
     * @return bool True if the data was successfully cached, false on failure
95
     */
96
    public function store($key, $data, $ttl = null, $overwrite = false)
97
    {
98
        if (null === $ttl) {
99
            $ttl = $this->options['ttl'];
100
        }
101
102
        if ($key === null) {
103
            return false;
104
        } elseif ($overwrite === false) {
105
            return apc_add($key, $data, $ttl);
106
        } else { // overwrite
107
108
            return apc_store($key, $data, $ttl);
109
        }
110
    }
111
112
    /**
113
     * Removes a stored variable from the.
114
     *
115
     * @link http://php.net/manual/en/function.apc-delete.php
116
     *
117
     * @param string $keys Identifier for the data
118
     *
119
     * @return bool Returns true on success or false on failure.
120
     */
121
    public function delete($keys)
122
    {
123
        $keys         = (array) $keys;
124
        $keys_deleted = 0;
0 ignored issues
show
Coding Style introduced by
$keys_deleted does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
125
126
        foreach ($keys as $key) {
127
            if (true === apc_delete($key)) {
128
                ++$keys_deleted;
0 ignored issues
show
Coding Style introduced by
$keys_deleted does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
129
            }
130
        }
131
132
        return (bool) $keys_deleted;
0 ignored issues
show
Coding Style introduced by
$keys_deleted does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
133
    }
134
135
    /**
136
     * Clears the APC cache.
137
     *
138
     * @link http://php.net/manual/en/function.apc-clear-cache.php
139
     *
140
     * @param string $cache_type [optional] all, user, opcode <p>
141
     *                           If cache_type is "user", the user cache will be cleared;
142
     *                           otherwise, the system cache (cached files) will be cleared. </p>
143
     *
144
     * @return bool Returns true on success or false on failure.
145
     */
146
    public function clear($cache_type = 'user')
147
    {
148
        if (extension_loaded('apcu')) {
149
            return apc_clear_cache();
150
        }
151
152
        if ($cache_type === 'all') {
0 ignored issues
show
Coding Style introduced by
$cache_type does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
153
            apc_clear_cache();
154
            apc_clear_cache('user');
155
            apc_clear_cache('opcode');
156
        }
157
158
        return apc_clear_cache($cache_type);
0 ignored issues
show
Coding Style introduced by
$cache_type does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
159
    }
160
161
    /**
162
     * Checks if a key exists in the cache.
163
     *
164
     * @param string $key Identifier for the data
165
     *
166
     * @return bool true|false
167
     */
168
    public function contains($key)
169
    {
170
        return apc_exists($key);
171
    }
172
173
    /**
174
     * Get stats and usage Informations for display from APC
175
     * 1. Shared Memory Allocation
176
     * 2. Cache Infos / Meta-Data.
177
     */
178
    public function stats()
179
    {
180
        $info = [];
181
        // Retrieve APC Version
182
        $info['version']    = phpversion('apc');
183
        $info['phpversion'] = phpversion();
184
185
        /*
186
         * ========================================================
187
         *   Retrieves APC's Shared Memory Allocation information
188
         * ========================================================
189
         */
190
        $info['sma_info'] = [];
191
192
        if (true === function_exists('apc_sma_info')) {
193
            $info['sma_info'] = apc_sma_info(true);
194
195
            // Calculate "APC Memory Size" (Number of Segments * Size of Segment)
196
            $memsize                      = $info['sma_info']['num_seg'] * $info['sma_info']['seg_size'];
197
            $info['sma_info']['mem_size'] = $memsize;
198
199
            // Calculate "APC Memory Usage" ( mem_size - avail_mem )
200
            $memusage                     = $info['sma_info']['mem_size'] - $info['sma_info']['avail_mem'];
201
            $info['sma_info']['mem_used'] = $memusage;
202
203
            // Calculate "APC Free Memory Percentage" ( mem_size*100/mem_used )
204
            $memsize_total                            = $info['sma_info']['avail_mem'] * 100;
0 ignored issues
show
Coding Style introduced by
$memsize_total does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
205
            $avail_mem_percent                        = sprintf('(%.1f%%)', $memsize_total  / $info['sma_info']['mem_size']);
0 ignored issues
show
Coding Style introduced by
$avail_mem_percent does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
206
            $info['sma_info']['mem_avail_percentage'] = $avail_mem_percent;
0 ignored issues
show
Coding Style introduced by
$avail_mem_percent does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
207
        }
208
209
        if (true === function_exists('apc_cache_info')) {
210
211
            // Retrieves cached information and meta-data from APC's data store
212
            $info['cache_info'] = apc_cache_info();
213
214
            #\Koch\Debug\Debug::printR(apc_cache_info());
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
215
            $info['cache_info']['cached_files']  = count($info['cache_info']['cache_list']);
216
            $info['cache_info']['deleted_files'] = count($info['cache_info']['deleted_list']);
217
218
            /*
219
             * ========================================================
220
             *   System Cache Informations
221
             * ========================================================
222
             */
223
            $info['system_cache_info'] = apc_cache_info('system', false); // set "false" for details
224
            // Calculate "APC Hit Rate Percentage"
225
            $hits = ($info['system_cache_info']['num_hits'] + $info['system_cache_info']['num_misses']);
226
227
            // div by zero fix
228
            if ($hits === 0) {
229
                $hits = 1;
230
            }
231
232
            $hit_rate_percentage                              = $info['system_cache_info']['num_hits'] * 100 / $hits;
0 ignored issues
show
Coding Style introduced by
$hit_rate_percentage does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
233
            $info['system_cache_info']['hit_rate_percentage'] = sprintf('(%.1f%%)', $hit_rate_percentage);
0 ignored issues
show
Coding Style introduced by
$hit_rate_percentage does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
234
235
            // Calculate "APC Miss Rate Percentage"
236
            $miss_percentage                                   = $info['system_cache_info']['num_misses'] * 100 / $hits;
0 ignored issues
show
Coding Style introduced by
$miss_percentage does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
237
            $info['system_cache_info']['miss_rate_percentage'] = sprintf('(%.1f%%)', $miss_percentage);
0 ignored issues
show
Coding Style introduced by
$miss_percentage does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
238
            $info['system_cache_info']['files_cached']         = count($info['system_cache_info']['cache_list']);
239
            $info['system_cache_info']['files_deleted']        = count($info['system_cache_info']['deleted_list']);
240
241
            // Request Rate (hits, misses) / cache requests/second
242
            $start_time = (time() - $info['system_cache_info']['start_time']);
0 ignored issues
show
Coding Style introduced by
$start_time does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
243
244
            // div by zero fix
245
            if ($start_time === 0) {
0 ignored issues
show
Coding Style introduced by
$start_time does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
246
                $start_time = 1;
0 ignored issues
show
Coding Style introduced by
$start_time does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
247
            }
248
249
            $rate                                  = (($info['system_cache_info']['num_hits'] + $info['system_cache_info']['num_misses']) / $start_time);
0 ignored issues
show
Coding Style introduced by
$start_time does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
250
            $info['system_cache_info']['req_rate'] = sprintf('%.2f', $rate);
251
252
            $hit_rate                              = ($info['system_cache_info']['num_hits']) / $start_time;
0 ignored issues
show
Coding Style introduced by
$hit_rate does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
253
            $info['system_cache_info']['hit_rate'] = sprintf('%.2f', $hit_rate);
0 ignored issues
show
Coding Style introduced by
$hit_rate does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
254
255
            $miss_rate                              = ($info['system_cache_info']['num_misses'] / $start_time);
0 ignored issues
show
Coding Style introduced by
$miss_rate does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
256
            $info['system_cache_info']['miss_rate'] = sprintf('%.2f', $miss_rate);
0 ignored issues
show
Coding Style introduced by
$miss_rate does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
257
258
            $insert_rate                              = (($info['system_cache_info']['num_inserts']) / $start_time);
0 ignored issues
show
Coding Style introduced by
$insert_rate does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
259
            $info['system_cache_info']['insert_rate'] = sprintf('%.2f', $insert_rate);
0 ignored issues
show
Coding Style introduced by
$insert_rate does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
260
261
            // size
262
            if (isset($info['system_cache_info']['mem_size']) and $info['system_cache_info']['mem_size'] > 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
263
                $info['system_cache_info']['size_files'] = Functions::getSize($info['system_cache_info']['mem_size']);
264
            } else {
265
                $info['system_cache_info']['size_files'] = 0;
266
            }
267
        }
268
269
        $info['settings'] = ini_get_all('apc');
270
271
        /*
272
         * ini_get_all array mod: for each accessvalue
273
         * add the name of the PHP ACCESS CONSTANTS as 'accessname'
274
         * @todo: cleanup?
275
         */
276
        foreach ($info['settings'] as $key => $value) {
277
            foreach ($value as $key2 => $value2) {
278
                if ($key2 === 'access') {
279
                    $name = '';
280
281
                    // accessvalue => constantname
282
                    if ($value2 === '1') {
283
                        $name = 'PHP_INI_USER';
284
                    }
285
                    if ($value2 === '2') {
286
                        $name = 'PHP_INI_PERDIR';
287
                    }
288
                    if ($value2 === '4') {
289
                        $name = 'PHP_INI_SYSTEM';
290
                    }
291
                    if ($value2 === '7') {
292
                        $name = 'PHP_INI_ALL';
293
                    }
294
295
                    // add accessname to the original array
296
                    $info['settings'][$key]['accessname'] = $name;
297
                    unset($name);
298
                }
299
            }
300
        }
301
302
        #$info['sma_info']['size_vars']  = Functions::getsize($cache_user['mem_size']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
303
304
        return $info;
305
    }
306
}
307