Completed
Push — dev ( 0d804d...daffda )
by Marc
02:18
created

ArtificerServiceProvider::addModel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 0
Metric Value
c 4
b 1
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php namespace Mascame\Artificer;
2
3
use App;
4
use Illuminate\Support\ServiceProvider;
5
use Illuminate\Support\Str;
6
use Mascame\Artificer\Extension\Booter;
7
use Mascame\Artificer\Model\Model;
8
use Mascame\Artificer\Model\ModelObtainer;
9
use Mascame\Artificer\Model\ModelSchema;
10
use Mascame\Artificer\Widget\Manager as WidgetManager;
11
use Mascame\Artificer\Plugin\Manager as PluginManager;
12
use Mascame\Extender\Event\Event;
13
use Mascame\Extender\Installer\FileInstaller;
14
use Mascame\Extender\Installer\FileWriter;
15
16
17
class ArtificerServiceProvider extends ServiceProvider {
18
19
	use AutoPublishable, ServiceProviderLoader;
20
	
21
	protected $name = 'admin';
22
23
    protected $corePlugins = [
24
        \Mascame\Artificer\LoginPlugin::class
25
    ];
26
27
	/**
28
	 * Indicates if loading of the provider is deferred.
29
	 *
30
	 * @var bool
31
	 */
32
	protected $defer = false;
33
34
	/**
35
	 * @var bool
36
	 */
37
	protected $isBootable = false;
38
39
	/**
40
	 * Bootstrap the application events.
41
	 *
42
	 * @return void
43
	 */
44
	public function boot()
45
	{
46
		if (! $this->isBootable) return;
47
		
48
		$this->addPublishableFiles();
49
50
		// Wait until app is ready for config to be published
51
		if (! $this->isPublished()) return;
52
53
		$this->providers(config('admin.providers'));
54
		$this->aliases(config('admin.aliases'));
55
		$this->commands(config('admin.commands'));
56
57
        Artificer::pluginManager()->boot();
58
        Artificer::widgetManager()->boot();
59
60
        $this->manageCorePlugins();
61
62
        Artificer::assetManager()->add(config('admin.assets', []));
63
64
        $this->requireFiles();
65
	}
66
67
    /**
68
     * Ensure core plugins are installed
69
     *
70
     * @throws \Exception
71
     */
72
	protected function manageCorePlugins() {
73
	    // Avoid installing plugins when using CLI
74
        if (App::runningInConsole() || App::runningUnitTests()) return true;
75
76
        $pluginManager = Artificer::pluginManager();
77
        $needsRefresh = false;
78
79
        foreach ($this->corePlugins as $corePlugin) {
80
            if (! $pluginManager->isInstalled($corePlugin)) {
81
                $installed = $pluginManager->installer()->install($corePlugin);
82
83
                if (! $installed) {
84
                    throw new \Exception("Unable to install Artificer core plugin {$corePlugin}");
85
                }
86
87
                $needsRefresh = true;
88
            }
89
        }
90
91
        // Refresh to allow changes made by core plugins to take effect
92
        if ($needsRefresh) {
93
            /**
94
             * File driver is slow... wait some seconds (else we would have too many redirects)
95
             *
96
             * Fortunately we only do this in the first run. Ye, I don't like it either.
97
             */
98
            sleep(2);
99
100
            header('Location: '. \URL::current());
101
            die();
102
        }
103
    }
104
105
    /**
106
     * Determines if is on admin
107
     *
108
     * @return bool
109
     */
110
    public function isBootable($path, $routePrefix = null) {
111
        if (App::runningInConsole() || App::runningUnitTests()) return true;
112
113
        return (
114
            $path == $routePrefix || Str::startsWith($path, $routePrefix . '/')
115
        );
116
    }
117
118
	private function requireFiles()
119
	{
120
		require_once __DIR__ . '/../routes/admin.php';
121
	}
122
123
	protected function getConfigPath() {
124
		return config_path($this->name) . DIRECTORY_SEPARATOR;
125
	}
126
127
	private function addPublishableFiles()
128
    {
129
		$this->publishes([
130
			__DIR__.'/../resources/assets' => public_path('packages/mascame/' . $this->name),
131
		], 'public');
132
133
        $this->publishes([
134
            __DIR__.'/../config/' => $this->getConfigPath(),
135
        ], 'config');
136
137
        $this->loadTranslationsFrom(__DIR__.'/../resources/lang', $this->name);
138
    }
139
140
	private function addLocalization()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
141
	{
142
		App::singleton('ArtificerLocalization', function () {
143
			return new Localization();
144
		});
145
	}
146
147
	private function addManagers()
148
	{
149
        App::singleton('ArtificerModel', function () {
150
            return new Model(new ModelSchema(new ModelObtainer()));
151
        });
152
153 View Code Duplication
		App::singleton('ArtificerWidgetManager', function() {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
154
            $widgetsConfig = $this->getConfigPath() . 'extensions/widgets.php';
155
156
            return new WidgetManager(
157
                new FileInstaller(new FileWriter(), $widgetsConfig),
158
                new Booter(),
159
                new Event(app('events'))
160
            );
161
        });
162
163 View Code Duplication
		App::singleton('ArtificerPluginManager', function() {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164
            $pluginsConfig = $this->getConfigPath() . 'extensions/plugins.php';
165
166
            return new PluginManager(
167
                new FileInstaller(new FileWriter(), $pluginsConfig),
168
                new \Mascame\Artificer\Plugin\Booter(),
169
                new Event(app('events'))
170
            );
171
		});
172
173
        App::singleton('ArtificerAssetManager', function() {
174
            return \Assets::config(array_merge([
175
                // Reset those dirs to avoid wrong paths
176
                'css_dir' => '',
177
                'js_dir' => '',
178
            ], config('admin.assets')));
179
        });
180
	}
181
182
	/**
183
	 * Register the service provider.
184
	 *
185
	 * @return void
186
	 */
187
	public function register()
188
	{
189
		// We still haven't modified config, that's why 'admin.admin'
190
		$routePrefix = config('admin.admin.routePrefix');
191
192
		// Avoid bloating the App with files that will not be needed
193
		$this->isBootable = $this->isBootable(request()->path(), $routePrefix);
194
195
		if (! $this->isBootable) return;
196
197
		// We need the config published before we can use this package!
198
		if ($this->isPublished()) {
199
			$this->loadConfig();
200
201
            // Todo
202
//			$this->addLocalization();
203
			$this->addManagers();
204
		}
205
	}
206
207
	/**
208
	 * Moves admin/admin.php keys to the root level for commodity
209
	 */
210
	protected function loadConfig() {
211
		$config = config('admin');
212
		$config = ['admin' => array_merge($config, $config['admin'])];
213
		unset($config['admin']['admin']);
214
215
		config()->set($config);
216
	}
217
218
	/**
219
	 * Get the services provided by the provider.
220
	 *
221
	 * @return array
222
	 */
223
	public function provides()
224
	{
225
		return [];
226
	}
227
228
}
229