htmlburger /
wpemerge
| 1 | <?php |
||
| 2 | /** |
||
| 3 | * @package WPEmerge |
||
| 4 | * @author Atanas Angelov <[email protected]> |
||
| 5 | * @copyright 2017-2019 Atanas Angelov |
||
| 6 | * @license https://www.gnu.org/licenses/gpl-2.0.html GPL-2.0 |
||
| 7 | * @link https://wpemerge.com/ |
||
| 8 | */ |
||
| 9 | |||
| 10 | namespace WPEmerge\ServiceProviders; |
||
| 11 | |||
| 12 | use Pimple\Container; |
||
| 13 | use WPEmerge\Support\Arr; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * Allows objects to extend the config. |
||
| 17 | */ |
||
| 18 | trait ExtendsConfigTrait { |
||
| 19 | /** |
||
| 20 | * Recursively replace default values with the passed config. |
||
| 21 | * - If either value is not an array, the config value will be used. |
||
| 22 | * - If both are an indexed array, the config value will be used. |
||
| 23 | * - If either is a keyed array, array_replace will be used with config having priority. |
||
| 24 | * |
||
| 25 | * @param mixed $default |
||
| 26 | * @param mixed $config |
||
| 27 | * @return mixed |
||
| 28 | */ |
||
| 29 | 4 | protected function replaceConfig( $default, $config ) { |
|
| 30 | 4 | if ( ! is_array( $default ) || ! is_array( $config ) ) { |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 31 | 3 | return $config; |
|
| 32 | } |
||
| 33 | |||
| 34 | 2 | $default_is_indexed = array_keys( $default ) === range( 0, count( $default ) - 1 ); |
|
| 35 | 2 | $config_is_indexed = array_keys( $config ) === range( 0, count( $config ) - 1 ); |
|
| 36 | |||
| 37 | 2 | if ( $default_is_indexed && $config_is_indexed ) { |
|
| 38 | 1 | return $config; |
|
| 39 | } |
||
| 40 | |||
| 41 | 2 | $result = $default; |
|
| 42 | |||
| 43 | 2 | foreach ( $config as $key => $value ) { |
|
| 44 | 2 | $result[ $key ] = $this->replaceConfig( Arr::get( $default, $key ), $value ); |
|
| 45 | } |
||
| 46 | |||
| 47 | 2 | return $result; |
|
| 48 | } |
||
| 49 | |||
| 50 | /** |
||
| 51 | * Extends the WP Emerge config in the container with a new key. |
||
| 52 | * |
||
| 53 | * @param Container $container |
||
| 54 | * @param string $key |
||
| 55 | * @param mixed $default |
||
| 56 | * @return void |
||
| 57 | */ |
||
| 58 | 4 | public function extendConfig( $container, $key, $default ) { |
|
| 59 | 4 | $config = isset( $container[ WPEMERGE_CONFIG_KEY ] ) ? $container[ WPEMERGE_CONFIG_KEY ] : []; |
|
| 60 | 4 | $config = Arr::get( $config, $key, $default ); |
|
| 61 | |||
| 62 | 4 | $container[ WPEMERGE_CONFIG_KEY ] = array_merge( |
|
| 63 | 4 | $container[ WPEMERGE_CONFIG_KEY ], |
|
| 64 | 4 | [$key => $this->replaceConfig( $default, $config )] |
|
| 65 | ); |
||
| 66 | 4 | } |
|
| 67 | } |
||
| 68 |