Completed
Push — master ( d438ae...624104 )
by Enrico
03:54
created

EnvProvider   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 1
dl 0
loc 48
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B register() 0 41 5
1
<?php
2
namespace EnvProvider;
3
4
use Pimple\Container;
5
use Pimple\ServiceProviderInterface;
6
7
class EnvProvider implements ServiceProviderInterface
8
{
9
    /**
10
     * @inheritdoc
11
     */
12 3
    public function register(Container $app)
13
    {
14 3
        $app['env.prefix'] = '';
15 3
		$app['env.vars'] = array();
16
		
17
		// predefined casting functions
18
		$app['env.cast.strval'] = $app->protect(function($str) {
19 2
			return strval($str);
20 3
		});
21
		
22
		$app['env.cast.boolean'] = $app->protect(function($str) {
23 1
			return ((0===strcasecmp('true',$str))||($str==='1'));
24 3
		});
25
		
26
		$app['env.cast.intval'] = $app->protect(function($str) {
27 1
			return intval($str);
28 3
		});
29
		
30
		$app['env.cast.json_decode'] = $app->protect(function($str) {
31 1
			return json_decode($str);
32 3
		});
33
		
34
		// default name builder
35
		$app['env.name.builder'] = $app->protect(function($parameterName) {
36 3
			return strtoupper((str_replace('.', '_', $parameterName)));;
37 3
		});
38
		
39 3
        $app['env.overload'] = function ($app) {
40 3
        	foreach($app['env.vars'] as $var => $cast){
41 3
        		$envVar =  $app['env.prefix'] . $app['env.name.builder']($var);
42 3
        		if( getenv($envVar)) {
43 3
        			if(isset($app[$cast])) {
44 2
        				$app[$var]= $app[$cast](getenv($envVar));
45
        			} else {
46 3
        				\trigger_error("Undefined cast service $cast");
47
        			}
48
        		}
49
        	}
50 2
			return $app;
51
        };
52 3
    }
53
54
}