Passed
Push — master ( 65b5b3...7a440c )
by Marcin
07:59 queued 10s
created

Util   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 39
rs 10
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A mergeConfig() 0 23 5
1
<?php
2
declare(strict_types=1);
3
4
namespace MarcinOrlowski\ResponseBuilder;
5
6
/**
7
 * Laravel API Response Builder
8
 *
9
 * @package   MarcinOrlowski\ResponseBuilder
10
 *
11
 * @author    Marcin Orlowski <mail (#) marcinOrlowski (.) com>
12
 * @copyright 2016-2019 Marcin Orlowski
13
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
14
 * @link      https://github.com/MarcinOrlowski/laravel-api-response-builder
15
 */
16
final class Util
17
{
18
    /**
19
     * Merges the configs together and takes multi-dimensional arrays into account.
20
     * Support for multi-dimensional config array. Built-in config merge only supports flat arrays.
21
     * Throws \RuntimeException if arrays stucture causes type conflics (i.e. you want to merge
22
     * array with int).
23
     *
24
     * @param array $original Array to merge other array into. Usually default values to overwrite.
25
     * @param array $merging Array with items to be merged into $original, overriding (primitives) or merging
26
     *                       (arrays) entries in destination array.
27
     *
28
     * @return array
29
     *
30
     * @throws \RuntimeException
31
     */
32
    public static function mergeConfig(array $original, array $merging): array
33
    {
34
        $array = $original;
35
        foreach ($merging as $m_key => $m_val) {
36
            if (array_key_exists($m_key, $original)) {
37
                $orig_type = gettype($original[ $m_key ]);
38
                $m_type = gettype($m_val);
39
                if ($orig_type !== $m_type) {
40
                    throw new \RuntimeException(
41
                        "Incompatible types. Cannot merge {$m_type} into {$orig_type} (key '{$m_key}').");
42
                }
43
44
                if (is_array($merging[ $m_key ])) {
45
                    $array[ $m_key ] = static::mergeConfig($original[ $m_key ], $m_val);
46
                } else {
47
                    $array[ $m_key ] = $m_val;
48
                }
49
            } else {
50
                $array[ $m_key ] = $m_val;
51
            }
52
        }
53
54
        return $array;
55
    }
56
57
}
58