| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\Framework\Foundation; |
| 4 |
|
| 5 |
use FluentSupport\Framework\Support\Arr; |
| 6 |
|
| 7 |
class Config |
| 8 |
{ |
| 9 |
/** |
| 10 |
* The config data |
| 11 |
* @var array |
| 12 |
*/ |
| 13 |
protected $data = []; |
| 14 |
|
| 15 |
/** |
| 16 |
* Construct the Config instance |
| 17 |
* @param array $data |
| 18 |
*/ |
| 19 |
public function __construct($data) |
| 20 |
{ |
| 21 |
$this->data = $data; |
| 22 |
} |
| 23 |
|
| 24 |
/** |
| 25 |
* Retrieve all config data |
| 26 |
* @return array |
| 27 |
*/ |
| 28 |
public function all() |
| 29 |
{ |
| 30 |
return $this->get(); |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* Retrieve specific item from config array. |
| 35 |
* |
| 36 |
* @param string $key |
| 37 |
* @param string $default |
| 38 |
* @return mixed |
| 39 |
*/ |
| 40 |
public function get($key = null, $default = null) |
| 41 |
{ |
| 42 |
$key = $this->resolveKey($key); |
| 43 |
|
| 44 |
return $key ? Arr::get($this->data, $key, $default) : $this->data; |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Get only specific items from the config array. |
| 49 |
* |
| 50 |
* @param string|array $key ($key1, $key2 or [$key1, $key2]) |
| 51 |
* @return array |
| 52 |
*/ |
| 53 |
public function only($key) |
| 54 |
{ |
| 55 |
$keys = array_map(function ($key) { |
| 56 |
return $this->resolveKey($key); |
| 57 |
}, is_Array($key) ? $key : func_get_args()); |
| 58 |
|
| 59 |
$result = []; |
| 60 |
|
| 61 |
foreach ($keys as $key) { |
| 62 |
$result[] = Arr::get($this->data, $key); |
| 63 |
} |
| 64 |
|
| 65 |
return array_values(array_filter($result)); |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
* Set an item into the config array on the fly. |
| 70 |
* @param string $key |
| 71 |
* @param mixed $value |
| 72 |
*/ |
| 73 |
public function set($key, $value) |
| 74 |
{ |
| 75 |
Arr::set($this->data, $key, $value); |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* Resolove the config key, add app. prefix if needed. |
| 80 |
* |
| 81 |
* @param string $key |
| 82 |
* @return string |
| 83 |
*/ |
| 84 |
protected function resolveKey($key) |
| 85 |
{ |
| 86 |
if (!$key) return $key; |
| 87 |
|
| 88 |
if (array_key_exists($key, $this->data)) { |
| 89 |
return $key; |
| 90 |
} |
| 91 |
|
| 92 |
return str_contains($key, '.') ? $key : "app.{$key}"; |
| 93 |
} |
| 94 |
} |
| 95 |
|