Completed
Push — master ( f98586...bb34f0 )
by Stefano
03:08
created

Options::loadENV()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 17
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
eloc 15
nc 6
nop 3
dl 0
loc 17
rs 8.8571
c 1
b 0
f 1
1
<?php
2
3
/**
4
 * Options
5
 *
6
 * A dictionary to handle application-wide options.
7
 *
8
 * @package core
9
 * @author [email protected]
10
 * @copyright Caffeina srl - 2015 - http://caffeina.it
11
 */
12
13
class Options extends Dictionary {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
14
    protected static $fields = null;
15
16
	/**
17
	 * Load a PHP configuration file (script must return array)
18
	 * @param  string $filepath The path of the PHP config file
19
	 * @param  string $prefix_path You can insert/update the loaded array to a specific key path, if omitted it will be merged with the whole dictionary
20
	 */
21
	public static function loadPHP($filepath,$prefix_path=null){
22
		ob_start();
23
		$results = include($filepath);
24
		ob_end_clean();
25
		if($results) static::loadArray($results,$prefix_path);
26
	}
27
28
	/**
29
	 * Load an INI configuration file
30
	 * @param  string $filepath The path of the INI config file
31
	 * @param  string $prefix_path You can insert/update the loaded array to a specific key path, if omitted it will be merged with the whole dictionary
32
	 */
33
	public static function loadINI($filepath,$prefix_path=null){
34
		$results = parse_ini_file($filepath,true);
35
		if($results) static::loadArray($results,$prefix_path);
36
	}
37
38
	/**
39
	 * Load a JSON configuration file
40
	 * @param  string $filepath The path of the JSON config file
41
	 * @param  string $prefix_path You can insert/update the loaded array to a specific key path, if omitted it will be merged with the whole dictionary
42
	 */
43
	public static function loadJSON($filepath,$prefix_path=null){
44
		$data = file_get_contents($filepath);
45
		$results = $data?json_decode($data,true):[];
46
		if($results) static::loadArray($results,$prefix_path);
47
	}
48
49
	/**
50
	 * Load an array to the configuration
51
	 * @param  array $array The array to load
52
	 * @param  string $prefix_path You can insert/update the loaded array to a specific key path, if omitted it will be merged with the whole dictionary
53
	 */
54
	public static function loadArray(array $array,$prefix_path=null){
55
		if (is_array($array)) {
56
			if ($prefix_path){
57
				static::set($prefix_path,$array);
58
			} else {
59
				static::merge($array);
60
			}
61
		}
62
	}
63
64
  /**
65
   * Load an ENV file
66
   * @param  string $dir The directory of the ENV file
67
   * @param  string $envname The filename for the ENV file (Default to `.env`)
68
   * @param  string $prefix_path You can insert/update the loaded array to a specific key path, if omitted it will be merged with the whole dictionary
69
   */
70
  public static function loadENV($dir,$envname='.env',$prefix_path=null){
0 ignored issues
show
Coding Style introduced by
loadENV uses the super-global variable $_ENV which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
71
    $dir = rtrim($dir,'/');
72
    $results = [];
73
    foreach(file("$dir/$envname", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line){
74
      $line = trim($line);
75
      if ($line[0]=='#' || strpos($line,'=')===false) continue;
76
      list($key,$value) = explode('=',$line,2);
77
      $key   = trim(str_replace(['export ', "'", '"'], '', $key));
78
      $value = stripslashes(trim($value,'"'));
79
      $results[$key] = preg_replace_callback('/\${([a-zA-Z0-9_]+)}/',function($m) use (&$results){
80
        return isset($results[$m[1]]) ? $results[$m[1]] : '';
81
      },$value);
82
      putenv("$key={$results[$key]}");
83
      $_ENV[$key] = $results[$key];
84
    }
85
    if($results) static::loadArray($results,$prefix_path);
1 ignored issue
show
Bug Best Practice introduced by
The expression $results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
86
  }
87
88
}
89