Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/Commands/stubs/scaffold/provider.stub
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ namespace $NAMESPACE$;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Nwidart\Modules\Traits\ConfigMergerTrait;
use Nwidart\Modules\Traits\PathNamespace;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

class $CLASS$ extends ServiceProvider
{
use PathNamespace;
use ConfigMergerTrait;

protected string $name = '$MODULE$';

Expand Down Expand Up @@ -100,7 +102,11 @@ class $CLASS$ extends ServiceProvider
$key = ($config === 'config.php') ? $this->nameLower : implode('.', $normalized);

$this->publishes([$file->getPathname() => config_path($config)], 'config');

// use the following if the module's config should replace the top-level config.
$this->merge_config_from($file->getPathname(), $key);
// or this if the module's config is a default value that can be replaced by the top-level config
//$this->mergeConfigDefaultsFrom($file->getPathname(), $key);
}
}
}
Expand Down
40 changes: 40 additions & 0 deletions src/Traits/ConfigMergerTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace Nwidart\Modules\Traits;

use Illuminate\Contracts\Foundation\CachesConfiguration;

trait ConfigMergerTrait
{
/**
* Merge configuration defaults from a file, allowing existing config to take precedence.
*
* @param string $path
* @param string $key
* @param bool $existingPrecedence Whether existing config takes precedence over module config
* @param bool $deep Whether to use deep merging (array_replace_recursive) or shallow merging (array_merge)
* @return void
*/
protected function mergeConfigDefaultsFrom($path, $key, $existingPrecedence = true, $deep = true): void
{
if (! ($this->app instanceof CachesConfiguration && $this->app->configurationIsCached())) {
$config = $this->app->make('config');
$existing = $config->get($key, []);
$new = require $path;

if ($deep) {
if ($existingPrecedence) {
$config->set($key, array_replace_recursive($new, $existing));
} else {
$config->set($key, array_replace_recursive($existing, $new));
}
} else {
if ($existingPrecedence) {
$config->set($key, array_merge($new, $existing));
} else {
$config->set($key, array_merge($existing, $new));
}
}
}
}
}
Loading