Last active
March 1, 2023 14:55
-
-
Save koenhoeijmakers/0a8e326ee3b12a826d73be38693fb647 to your computer and use it in GitHub Desktop.
A Laravel ServiceProvider that actually merges the Config properly, taking multi-dimensional arrays into account.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Providers; | |
use Illuminate\Support\Arr; | |
use Illuminate\Support\ServiceProvider; | |
class BaseServiceProvider extends ServiceProvider | |
{ | |
/** | |
* Perform post-registration booting of services. | |
* | |
* @return void | |
*/ | |
public function boot() | |
{ | |
// | |
} | |
/** | |
* Register bindings in the container. | |
* | |
* @return void | |
*/ | |
public function register() | |
{ | |
// | |
} | |
/** | |
* Merge the given configuration with the existing configuration. | |
* | |
* @param string $path | |
* @param string $key | |
* @return void | |
*/ | |
protected function mergeConfigFrom($path, $key) | |
{ | |
$config = $this->app['config']->get($key, []); | |
$this->app['config']->set($key, $this->mergeConfig(require $path, $config)); | |
} | |
/** | |
* Merges the configs together and takes multi-dimensional arrays into account. | |
* | |
* @param array $original | |
* @param array $merging | |
* @return array | |
*/ | |
protected function mergeConfig(array $original, array $merging) | |
{ | |
$array = array_merge($original, $merging); | |
foreach ($original as $key => $value) { | |
if (! is_array($value)) { | |
continue; | |
} | |
if (! Arr::exists($merging, $key)) { | |
continue; | |
} | |
if (is_numeric($key)) { | |
continue; | |
} | |
$array[$key] = $this->mergeConfig($value, $merging[$key]); | |
} | |
return $array; | |
} | |
} |
My bad, i renamed the method but actually forgot the call, thanks for noticing 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot for this!
There is a small issue however.
On lines 41 and 68 you're calling the function
$this->mergeConfig
but in reality that function is called$this->mergeConfigs
(plural).