Passed
Push — master ( df7929...33655b )
by Atanas
02:06
created

ExtendsConfigTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 35.29%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 8
eloc 16
c 1
b 0
f 1
dl 0
loc 47
ccs 6
cts 17
cp 0.3529
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A extendConfig() 0 7 2
A replaceConfig() 0 19 6
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
	protected function replaceConfig( $default, $config ) {
30
		if ( ! is_array( $default ) || ! is_array( $config ) ) {
31
			return $config;
32
		}
33
34
		$default_is_indexed = array_keys( $default ) === range( 0, count( $default ) - 1 );
35
		$config_is_indexed = array_keys( $config ) === range( 0, count( $config ) - 1 );
36
37
		if ( $default_is_indexed && $config_is_indexed ) {
38
			return $config;
39
		}
40
41
		$result = $default;
42
43
		foreach ( $config as $key => $value ) {
44
			$result[ $key ] = $this->replaceConfig( Arr::get( $default, $key ), $value );
45
		}
46
47
		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