Options::loadJSON()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
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 {
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 View Code Duplication
  public static function loadPHP($filepath,$prefix_path=null){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
22
    ob_start();
23
    $results = include($filepath);
24
    ob_end_clean();
25
    if($results) {
26
      $results = static::filterWith(["load.php", "load"], $results);
27
      static::loadArray($results,$prefix_path);
28
    }
29
  }
30
31
  /**
32
	 * Load an INI configuration file
33
	 * @param  string $filepath The path of the INI config file
34
	 * @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
35
	 */
36 View Code Duplication
  public static function loadINI($filepath,$prefix_path=null){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
37
    $results = parse_ini_file($filepath,true);
38
    if($results) {
0 ignored issues
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...
39
      $results = static::filterWith(["load.ini", "load"], $results);
40
      static::loadArray($results,$prefix_path);
41
    }
42
  }
43
44
  /**
45
   * Load a JSON configuration file
46
   * @param  string $filepath The path of the JSON config file
47
   * @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
48
   */
49
  public static function loadJSON($filepath,$prefix_path=null){
50
    $data = file_get_contents($filepath);
51
    $results = $data?json_decode($data,true):[];
52
    if($results) {
53
      $results = static::filterWith(["load.json", "load"], $results);
54
      static::loadArray($results,$prefix_path);
55
    }
56
  }
57
58
  /**
59
	 * Load an array to the configuration
60
	 * @param  array $array The array to load
61
	 * @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
62
	 */
63
  public static function loadArray(array $array,$prefix_path=null){
64
    $array = static::filterWith(["load.array", "load"], $array);
65
    if ($prefix_path){
0 ignored issues
show
Bug Best Practice introduced by
The expression $prefix_path of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
66
      static::set($prefix_path,$array);
67
    } else {
68
      static::merge($array);
69
    }
70
    self::trigger('loaded');
71
  }
72
73
  /**
74
   * Load an ENV file
75
   * @param  string $dir The directory of the ENV file
76
   * @param  string $envname The filename for the ENV file (Default to `.env`)
77
   * @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
78
   */
79
  public static function loadENV($dir,$envname='.env',$prefix_path=null){
80
    $dir = rtrim($dir,'/');
81
    $results = [];
82
    foreach(file("$dir/$envname", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line){
83
      $line = trim($line);
84
      if ($line[0]=='#' || strpos($line,'=')===false) continue;
85
      list($key,$value) = explode('=',$line,2);
86
      $key   = trim(str_replace(['export ', "'", '"'], '', $key));
87
      $value = stripslashes(trim($value,'"\''));
88
      $results[$key] = preg_replace_callback('/\${([a-zA-Z0-9_]+)}/',function($m) use (&$results){
89
        return isset($results[$m[1]]) ? $results[$m[1]] : '';
90
      },$value);
91
      putenv("$key={$results[$key]}");
92
      $_ENV[$key] = $results[$key];
93
    }
94
    if($results) {
0 ignored issues
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...
95
      $results = static::filterWith(["load.env", "load"], $results);
96
      static::loadArray($results,$prefix_path);
97
    }
98
  }
99
100
}
101