summaryrefslogtreecommitdiff
path: root/src/Config/ConfigServiceProvider.php
blob: aff7918ddc1f0d2f4970f897fe95bcadbdf9b20b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php

namespace Engelsystem\Config;

use Engelsystem\Application;
use Engelsystem\Container\ServiceProvider;
use Engelsystem\Models\EventConfig;
use Exception;
use Illuminate\Database\QueryException;

class ConfigServiceProvider extends ServiceProvider
{
    /** @var array */
    protected $configFiles = ['config.default.php', 'config.php'];

    /** @var EventConfig */
    protected $eventConfig;

    /**
     * @param Application $app
     * @param EventConfig $eventConfig
     */
    public function __construct(Application $app, EventConfig $eventConfig = null)
    {
        parent::__construct($app);

        $this->eventConfig = $eventConfig;
    }

    public function register()
    {
        $config = $this->app->make(Config::class);
        $this->app->instance(Config::class, $config);
        $this->app->instance('config', $config);

        foreach ($this->configFiles as $file) {
            $file = $this->getConfigPath($file);

            if (!file_exists($file)) {
                continue;
            }

            $configuration = array_replace_recursive(
                $config->get(null),
                require $file
            );
            $config->set($configuration);
        }

        if (empty($config->get(null))) {
            throw new Exception('Configuration not found');
        }
    }

    public function boot()
    {
        if (!$this->eventConfig) {
            return;
        }

        /** @var Config $config */
        $config = $this->app->get('config');
        try {
            /** @var EventConfig[] $values */
            $values = $this->eventConfig->newQuery()->get(['name', 'value']);
        } catch (QueryException $e) {
            return;
        }

        foreach ($values as $option) {
            $data = $option->value;

            if (is_array($data) && $config->has($option->name)) {
                $data = array_replace_recursive(
                    $config->get($option->name),
                    $data
                );
            }

            $config->set($option->name, $data);
        }
    }

    /**
     * Get the config path
     *
     * @param string $path
     * @return string
     */
    protected function getConfigPath($path = ''): string
    {
        return config_path($path);
    }
}