|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace CodeTechCMS\Settingable\Providers; |
| 4 | + |
| 5 | +use CodeTechCMS\Settingable\Models\ModelSetting; |
| 6 | +use Illuminate\Support\Facades\Config; |
| 7 | +use Illuminate\Support\ServiceProvider; |
| 8 | + |
| 9 | +class SettingableServiceProvider extends ServiceProvider |
| 10 | +{ |
| 11 | + /** |
| 12 | + * Register services. |
| 13 | + * |
| 14 | + * @return void |
| 15 | + */ |
| 16 | + public function register() |
| 17 | + { |
| 18 | + $this->mergeConfigFrom( |
| 19 | + __DIR__ . '/../config/settingable.php', 'settingable' |
| 20 | + ); |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Bootstrap services. |
| 25 | + * |
| 26 | + * @return void |
| 27 | + */ |
| 28 | + public function boot() |
| 29 | + { |
| 30 | + // Load migrations from custom path |
| 31 | + $this->loadMigrationsFrom(__DIR__ . '/../database/migrations'); |
| 32 | + |
| 33 | + $this->setPublishableFiles(); |
| 34 | + |
| 35 | + if (config('settingable.load_into_memory')) { |
| 36 | + $this->loadSettings(); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Set which files can be published. |
| 42 | + */ |
| 43 | + private function setPublishableFiles() |
| 44 | + { |
| 45 | + $this->publishes([ |
| 46 | + __DIR__ . '/../config/settingable.php' => config_path('settingable.php') |
| 47 | + ], 'config'); |
| 48 | + |
| 49 | + $this->publishes([ |
| 50 | + __DIR__ . '/../database/migrations/' => database_path('migrations') |
| 51 | + ], 'migrations'); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Load settings into memory. |
| 56 | + */ |
| 57 | + private function loadSettings() |
| 58 | + { |
| 59 | + $settings = ModelSetting::select('root', 'path', 'value')->get(); |
| 60 | + |
| 61 | + $results = []; |
| 62 | + |
| 63 | + foreach ($settings as $setting) { |
| 64 | + $fullPath = $setting->root . '.' . $setting->path; |
| 65 | + |
| 66 | + $keys = explode('.', $fullPath); |
| 67 | + |
| 68 | + $temp = &$results; |
| 69 | + |
| 70 | + foreach ($keys as $key) { |
| 71 | + $temp = &$temp[$key]; |
| 72 | + } |
| 73 | + |
| 74 | + $temp = $setting->value; |
| 75 | + |
| 76 | + unset($temp); |
| 77 | + } |
| 78 | + |
| 79 | + foreach ($results as $key => $result) { |
| 80 | + if (!is_array($result)) { |
| 81 | + Config::set($key, $result); |
| 82 | + |
| 83 | + continue; |
| 84 | + } |
| 85 | + |
| 86 | + $configs = config($key) ? array_merge(config($key), $result) : $result; |
| 87 | + |
| 88 | + Config::set($key, $configs); |
| 89 | + } |
| 90 | + } |
| 91 | +} |
0 commit comments