| 1 |
<?php |
| 2 |
/** |
| 3 |
* Resolves configuration items from multiple sources. |
| 4 |
* |
| 5 |
* @package SolidWP\Performance |
| 6 |
*/ |
| 7 |
|
| 8 |
declare( strict_types=1 ); |
| 9 |
|
| 10 |
namespace SolidWP\Performance\Config; |
| 11 |
|
| 12 |
/** |
| 13 |
* Resolves configuration items from multiple sources. |
| 14 |
* |
| 15 |
* @package SolidWP\Performance |
| 16 |
*/ |
| 17 |
final class Config_Resolver { |
| 18 |
|
| 19 |
/** |
| 20 |
* Merge configuration arrays, with values from the last array overriding values from the |
| 21 |
* previous arrays. |
| 22 |
* |
| 23 |
* @param array<string, mixed> ...$configs The different config sources. |
| 24 |
* |
| 25 |
* @return array |
| 26 |
*/ |
| 27 |
public function merge_configs( array ...$configs ): array { |
| 28 |
$merged = []; |
| 29 |
|
| 30 |
foreach ( $configs as $config ) { |
| 31 |
$merged = $this->replace_recursive( $merged, $config ); |
| 32 |
} |
| 33 |
|
| 34 |
return $merged; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Recursively merges two arrays, with values from the second array overriding those in the first. |
| 39 |
* |
| 40 |
* This method performs a deep merge: |
| 41 |
* - If both values for a key are arrays, it merges them recursively. |
| 42 |
* - If one value is an array and the other is a scalar, the scalar overrides the array. |
| 43 |
* - For numeric keys in indexed arrays, the values from the second array replace those in the first array. |
| 44 |
* |
| 45 |
* @param mixed[] $array1 The base array to merge into. |
| 46 |
* @param mixed[] $array2 The overriding array. |
| 47 |
* |
| 48 |
* @return mixed[] |
| 49 |
*/ |
| 50 |
private function replace_recursive( array $array1, array $array2 ): array { |
| 51 |
foreach ( $array2 as $key => $value ) { |
| 52 |
if ( is_array( $value ) && array_is_list( $value ) === false ) { |
| 53 |
$array1[ $key ] = $this->replace_recursive( $array1[ $key ] ?? [], $value ); |
| 54 |
} else { |
| 55 |
$array1[ $key ] = $value; |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
return $array1; |
| 60 |
} |
| 61 |
} |
| 62 |
|