Completed
Push — 2.0 ( 07e083...8b0753 )
by Marco
03:10 queued 01:10
created

ConfigurationParser::BuildApcuProvider()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 2
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php namespace Comodojo\Cache\Components;
2
3
use \Comodojo\Foundation\Base\Configuration;
4
use \Comodojo\Foundation\Validation\DataFilter;
5
use \Comodojo\Foundation\Utils\ArrayOps;
6
use \Psr\Log\LoggerInterface;
7
use \Comodojo\Cache\Providers\Apc as CacheApc;
8
use \Comodojo\Cache\Providers\Apcu as CacheApcu;
9
use \Comodojo\Cache\Providers\Filesystem as CacheFilesystem;
10
use \Comodojo\Cache\Providers\Memcached as CacheMemcached;
11
use \Comodojo\Cache\Providers\Memory as CacheMemory;
12
use \Comodojo\Cache\Providers\PhpRedis as CachePhpRedis;
13
use \Comodojo\Cache\Providers\Vacuum as CacheVacuum;
14
15
/**
16
 * @package     Comodojo Cache
17
 * @author      Marco Giovinazzi <[email protected]>
18
 * @license     MIT
19
 *
20
 * LICENSE:
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
28
 * THE SOFTWARE.
29
 */
30
31
class ConfigurationParser {
32
33
    protected static $algorithms = array(
34
        'PICK_FIRST' => 1,
35
        'PICK_LAST' => 2,
36
        'PICK_RANDOM' => 3,
37
        'PICK_BYWEIGHT' => 4,
38
        'PICK_ALL' => 4,
39
        'PICK_TRAVERSE' => 6
40
    );
41
42 2
    public static function parse(Configuration $configuration, LoggerInterface $logger) {
43
44 2
        list($enable, $manager) = self::parseManagerConfiguration($configuration, $logger);
45 2
        $providers = self::buildProviders($configuration, $logger);
46
47
        return [
48
            $enable,
49
            $manager,
50
            $providers
51
        ];
52
53
    }
54
55 1
    protected static function BuildApcProvider(LoggerInterface $logger) {
56
57 1
        return new CacheApc([], $logger);
58
59
    }
60
61
    protected static function BuildApcuProvider(LoggerInterface $logger) {
62
63
        return new CacheApcu([], $logger);
64
65
    }
66
67
    protected static function BuildFilesystemProvider(array $properties, LoggerInterface $logger) {
68
69
        return new CacheFilesystem($properties, $logger);
70
71
    }
72
73
    protected static function BuildMemcachedProvider(array $properties, LoggerInterface $logger) {
74
75
        return new CacheMemcached($properties, $logger);
76
77
    }
78
79
    protected static function BuildMemoryProvider(LoggerInterface $logger) {
80
81
        return new CacheMemory([], $logger);
82
83
    }
84
85
    protected static function BuildPhpRedisProvider(array $properties, LoggerInterface $logger) {
86
87
        return new CachePhpRedis($properties, $logger);
88
89
    }
90
91
    protected static function BuildVacuumProvider(LoggerInterface $logger) {
92
93
        return new CacheVacuum([], $logger);
94
95
    }
96
97 2
    protected static function parseManagerConfiguration(Configuration $configuration, LoggerInterface $logger) {
98
99 2
        $cache = $configuration->get('cache');
100
101
        $stdConfig = [
102 2
            'pick_mode' => null,
103 2
            'logger' => $logger,
104 2
            'align_cache' => true,
105
            'flap_interval' => null
106 2
        ];
107
108 2
        $enable = true;
109
110 2
        if ( $cache !== null && is_array($cache) ) {
111 2
            $lower_cache = array_change_key_case($cache, CASE_LOWER);
112 2
            if ( isset($lower_cache['logger']) ) unset($lower_cache['logger']);
113 2
            $stdConfig = array_merge($stdConfig, array_intersect_key($lower_cache, $stdConfig));
114 2
            if ( isset($lower_cache['enable']) && $lower_cache['enable'] === false ) $enable = false;
115 2
        }
116
117 2
        if ( $stdConfig['pick_mode'] !== null ) $stdConfig['pick_mode'] = self::getPickMode($stdConfig['pick_mode']);
118
119 2
        return [$enable, array_values($stdConfig)];
120
121
    }
122
123 2
    protected static function buildProviders(Configuration $configuration, LoggerInterface $logger) {
124
125 2
        $cache = $configuration->get('cache');
126 2
        $build = [];
127
128 2
        if ( $cache === null ) return $build;
129
130 2
        $lower_cache = array_change_key_case($cache, CASE_LOWER);
131
132 2
        if ( !isset($lower_cache['providers']) || !is_array($lower_cache['providers']) ) return $build;
133
134 2
        $providers = $lower_cache['providers'];
135
136 2
        foreach ( $providers as $name => $specs ) {
137
138 2
            if ( !is_array($specs) ) {
139
                $logger->error("Invalid specs for cache provider: $name");
140
                continue;
141
            }
142
143 2
            $spec = array_change_key_case($specs, CASE_LOWER);
144
145 2
            if ( empty($spec['type']) ) {
146
                $logger->error("Missing type for cache provider: $name");
147
                continue;
148
            }
149
150 2
            $type = strtoupper($spec['type']);
151
152
            switch ( $type ) {
153
154 2
                case 'APC':
155 2
                    $provider = static::BuildApcProvider($logger);
156
                    break;
157
158
                case 'APCU':
159
                    $provider = static::BuildApcuProvider($logger);
160
                    break;
161
162
                case 'FILESYSTEM':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
163
164
                    $stdConfig = [
165
                        'cache_folder' => null
166
                    ];
167
168
                    if ( isset($spec['cache_folder']) ) {
169
                        if ( $spec['cache_folder'][0] == "/" ) {
170
                            $stdConfig['cache_folder'] = $spec['cache_folder'];
171
                        } else {
172
                            $stdConfig['cache_folder'] = $configuration->get('base-path')."/".$spec['cache_folder'];
173
                        }
174
                    }
175
176
                    $provider = static::BuildFilesystemProvider($stdConfig, $logger);
177
178
                    break;
179
180
                case 'MEMCACHED':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
181
182
                    $valid_values = [
183
                        'server',
184
                        'port',
185
                        'weight',
186
                        'persistent_id',
187
                        'username',
188
                        'password'
189
                    ];
190
191
                    $stdConfig = ArrayOps::filterByKeys($valid_values, $spec);
192
193
                    $provider = static::BuildMemcachedProvider($stdConfig, $logger);
194
                    break;
195
196
                case 'MEMORY':
197
                    $provider = static::BuildMemoryProvider($logger);
198
                    break;
199
200
                case 'PHPREDIS':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
201
202
                    $valid_values = [
203
                        'server',
204
                        'port',
205
                        'timeout',
206
                        'logger',
207
                        'password'
208
                    ];
209
210
                    $stdConfig = ArrayOps::filterByKeys($valid_values, $spec);
211
212
                    $provider = static::BuildPhpRedisProvider($stdConfig, $logger);
213
                    break;
214
215
                case 'VACUUM':
216
                    $provider = static::BuildVacuumProvider($logger);
217
                    break;
218
219
                default:
220
                    $logger->error("Unknown type $type for cache provider: $name");
221
                    continue 2;
222
                    break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
223
224
            }
225
226
            $build[$name] = (object) [
227
                "instance" => $provider,
228
                "weight" => isset($spec['weight']) ?
229
                    DataFilter::filterInteger($spec['weight'], 0, 100, 0) : 0
230
            ];
231
232
        }
233
234
        return $build;
235
236
    }
237
238 2
    protected static function getPickMode($algorithm = null) {
239
240 2
        $algorithm = strtoupper($algorithm);
241
242 2
        if ( array_key_exists($algorithm, self::$algorithms) ) return self::$algorithms[$algorithm];
243
244
        return self::$algorithms['PICK_FIRST'];
245
246
    }
247
248
}
249