Passed
Pull Request — 1.2 (#405)
by
unknown
08:49
created

TwillServiceProvider::publishMigrations()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
nc 2
nop 0
dl 0
loc 12
ccs 8
cts 8
cp 1
crap 2
rs 10
c 4
b 0
f 0
1
<?php
2
3
namespace A17\Twill;
4
5
use A17\Twill\Commands\Build;
6
use A17\Twill\Commands\CreateSuperAdmin;
7
use A17\Twill\Commands\GenerateBlocks;
8
use A17\Twill\Commands\Install;
9
use A17\Twill\Commands\ModuleMake;
10
use A17\Twill\Commands\RefreshLQIP;
11
use A17\Twill\Commands\Update;
12
use A17\Twill\Http\ViewComposers\ActiveNavigation;
13
use A17\Twill\Http\ViewComposers\CurrentUser;
14
use A17\Twill\Http\ViewComposers\FilesUploaderConfig;
15
use A17\Twill\Http\ViewComposers\MediasUploaderConfig;
16
use A17\Twill\Http\ViewComposers\Localization;
17
use A17\Twill\Models\Block;
18
use A17\Twill\Models\File;
19
use A17\Twill\Models\Media;
20
use A17\Twill\Models\User;
21
use A17\Twill\Services\FileLibrary\FileService;
22
use A17\Twill\Services\MediaLibrary\ImageService;
23
use Astrotomic\Translatable\TranslatableServiceProvider;
24
use Cartalyst\Tags\TagsServiceProvider;
25
use Illuminate\Database\Eloquent\Relations\Relation;
26
use Illuminate\Foundation\AliasLoader;
27
use Illuminate\Support\Facades\View;
28
use Illuminate\Support\ServiceProvider;
29
use Illuminate\Support\Str;
30
use Spatie\Activitylog\ActivitylogServiceProvider;
31
32
class TwillServiceProvider extends ServiceProvider
33
{
34
35
    /**
36
     * The Twill version.
37
     *
38
     * @var string
39
     */
40
    const VERSION = '2.0.0';
41
42
    /**
43
     * Service providers to be registered.
44
     *
45
     * @var string[]
46
     */
47
    protected $providers = [
48
        RouteServiceProvider::class,
49
        AuthServiceProvider::class,
50
        ValidationServiceProvider::class,
51
        TranslatableServiceProvider::class,
52
        TagsServiceProvider::class,
53
        ActivitylogServiceProvider::class,
54
    ];
55
56
    private $migrationsCounter = 0;
0 ignored issues
show
introduced by
The private property $migrationsCounter is not used, and could be removed.
Loading history...
57
58
    /**
59
     * Bootstraps the package services.
60
     *
61
     * @return void
62
     */
63 59
    public function boot()
64
    {
65 59
        $this->requireHelpers();
66
67 59
        $this->publishConfigs();
68 59
        $this->publishMigrations();
69 59
        $this->publishAssets();
70
71 59
        $this->registerCommands();
72
73 59
        $this->registerAndPublishViews();
74
75 59
        $this->extendBlade();
76 59
        $this->addViewComposers();
77 59
    }
78
79
    /**
80
     * @return void
81
     */
82 59
    private function requireHelpers()
83
    {
84 59
        require_once __DIR__ . '/Helpers/routes_helpers.php';
85 59
        require_once __DIR__ . '/Helpers/i18n_helpers.php';
86 59
        require_once __DIR__ . '/Helpers/media_library_helpers.php';
87 59
        require_once __DIR__ . '/Helpers/frontend_helpers.php';
88 59
        require_once __DIR__ . '/Helpers/migrations_helpers.php';
89 59
        require_once __DIR__ . '/Helpers/helpers.php';
90 59
    }
91
92
    /**
93
     * Registers the package services.
94
     *
95
     * @return void
96
     */
97 59
    public function register()
98
    {
99 59
        $this->mergeConfigs();
100
101 59
        $this->registerProviders();
102 59
        $this->registerAliases();
103
104 59
        Relation::morphMap([
105 59
            'users' => User::class,
106
            'media' => Media::class,
107
            'files' => File::class,
108
            'blocks' => Block::class,
109
        ]);
110
111 59
        config(['twill.version' => $this->version()]);
112 59
    }
113
114
    /**
115
     * Registers the package service providers.
116
     *
117
     * @return void
118
     */
119 59
    private function registerProviders()
120
    {
121 59
        foreach ($this->providers as $provider) {
122 59
            $this->app->register($provider);
123
        }
124
125 59
        if (config('twill.enabled.media-library')) {
126
            $this->app->singleton('imageService', function () {
127 7
                return $this->app->make(config('twill.media_library.image_service'));
128 59
            });
129
        }
130
131 59
        if (config('twill.enabled.file-library')) {
132
            $this->app->singleton('fileService', function () {
133 3
                return $this->app->make(config('twill.file_library.file_service'));
134 59
            });
135
        }
136 59
    }
137
138
    /**
139
     * Registers the package facade aliases.
140
     *
141
     * @return void
142
     */
143 59
    private function registerAliases()
144
    {
145 59
        $loader = AliasLoader::getInstance();
146
147 59
        if (config('twill.enabled.media-library')) {
148 59
            $loader->alias('ImageService', ImageService::class);
149
        }
150
151 59
        if (config('twill.enabled.file-library')) {
152 59
            $loader->alias('FileService', FileService::class);
153
        }
154
155 59
    }
156
157
    /**
158
     * Defines the package configuration files for publishing.
159
     *
160
     * @return void
161
     */
162 59
    private function publishConfigs()
163
    {
164 59
        if (config('twill.enabled.users-management')) {
165 59
            config(['auth.providers.twill_users' => [
166 59
                'driver' => 'eloquent',
167
                'model' => User::class,
168
            ]]);
169
170 59
            config(['auth.guards.twill_users' => [
171 59
                'driver' => 'session',
172
                'provider' => 'twill_users',
173
            ]]);
174
175 59
            config(['auth.passwords.twill_users' => [
176 59
                'provider' => 'twill_users',
177 59
                'table' => config('twill.password_resets_table', 'twill_password_resets'),
178 59
                'expire' => 60,
179
            ]]);
180
        }
181
182 59
        config(['activitylog.enabled' => config('twill.enabled.dashboard') ? true : config('twill.enabled.activitylog')]);
183 59
        config(['activitylog.subject_returns_soft_deleted_models' => true]);
184
185 59
        config(['analytics.service_account_credentials_json' => config('twill.dashboard.analytics.service_account_credentials_json', storage_path('app/analytics/service-account-credentials.json'))]);
186
187 59
        $this->publishes([__DIR__ . '/../config/twill-publish.php' => config_path('twill.php')], 'config');
188 59
        $this->publishes([__DIR__ . '/../config/twill-navigation.php' => config_path('twill-navigation.php')], 'config');
189 59
        $this->publishes([__DIR__ . '/../config/translatable.php' => config_path('translatable.php')], 'config');
190 59
    }
191
192
    /**
193
     * Merges the package configuration files into the given configuration namespaces.
194
     *
195
     * @return void
196
     */
197 59
    private function mergeConfigs()
198
    {
199 59
        $this->mergeConfigFrom(__DIR__ . '/../config/twill.php', 'twill');
200 59
        $this->mergeConfigFrom(__DIR__ . '/../config/frontend.php', 'twill.frontend');
201 59
        $this->mergeConfigFrom(__DIR__ . '/../config/debug.php', 'twill.debug');
202 59
        $this->mergeConfigFrom(__DIR__ . '/../config/seo.php', 'twill.seo');
203 59
        $this->mergeConfigFrom(__DIR__ . '/../config/blocks.php', 'twill.block_editor');
204 59
        $this->mergeConfigFrom(__DIR__ . '/../config/enabled.php', 'twill.enabled');
205 59
        $this->mergeConfigFrom(__DIR__ . '/../config/file-library.php', 'twill.file_library');
206 59
        $this->mergeConfigFrom(__DIR__ . '/../config/media-library.php', 'twill.media_library');
207 59
        $this->mergeConfigFrom(__DIR__ . '/../config/imgix.php', 'twill.imgix');
208 59
        $this->mergeConfigFrom(__DIR__ . '/../config/glide.php', 'twill.glide');
209 59
        $this->mergeConfigFrom(__DIR__ . '/../config/dashboard.php', 'twill.dashboard');
210 59
        $this->mergeConfigFrom(__DIR__ . '/../config/oauth.php', 'twill.oauth');
211 59
        $this->mergeConfigFrom(__DIR__ . '/../config/disks.php', 'filesystems.disks');
212 59
        $this->mergeConfigFrom(__DIR__ . '/../config/services.php', 'services');
213 59
    }
214
215 59
    private function publishMigrations()
216
    {
217 59
        if (config('twill.load_default_migrations_from_twill', true)) {
218 59
            $this->loadMigrationsFrom(__DIR__ . '/../migrations/default');
219
        }
220
221 59
        $this->publishes([
222 59
            __DIR__ . '/../migrations/default' => database_path('migrations'),
223 59
        ], 'migrations');
224
225 59
        $this->publishOptionalMigration('users-2fa');
226 59
        $this->publishOptionalMigration('users-oauth');
227 59
    }
228
229 59
    private function publishOptionalMigration($feature)
230
    {
231 59
        if (config('twill.enabled.' . $feature, false)) {
232 55
            $this->loadMigrationsFrom(__DIR__ . '/../migrations/optional/' . $feature);
233
234 55
            $this->publishes([
235 55
                __DIR__ . '/../migrations/optional/' . $feature => database_path('migrations'),
236 55
            ], 'migrations');
237
        }
238 59
    }
239
240
    /**
241
     * @return void
242
     */
243 59
    private function publishAssets()
244
    {
245 59
        $this->publishes([
246 59
            __DIR__ . '/../dist' => public_path(),
247 59
        ], 'assets');
248 59
    }
249
250
    /**
251
     * @return void
252
     */
253 59
    private function registerAndPublishViews()
254
    {
255 59
        $viewPath = __DIR__ . '/../views';
256
257 59
        $this->loadViewsFrom($viewPath, 'twill');
258 59
        $this->loadTranslationsFrom($viewPath . '/lang', 'twill');
259 59
        $this->publishes([$viewPath => resource_path('views/vendor/twill')], 'views');
260 59
    }
261
262
    /**
263
     * @return void
264
     */
265 59
    private function registerCommands()
266
    {
267 59
        $this->commands([
268 59
            Install::class,
269
            ModuleMake::class,
270
            CreateSuperAdmin::class,
271
            RefreshLQIP::class,
272
            GenerateBlocks::class,
273
            Build::class,
274
            Update::class,
275
        ]);
276 59
    }
277
278
    /**
279
     * @param string $view
280
     * @param string $expression
281
     * @return string
282
     */
283 5
    private function includeView($view, $expression)
284
    {
285 5
        list($name) = str_getcsv($expression, ',', '\'');
286
287 5
        $partialNamespace = view()->exists('admin.' . $view . $name) ? 'admin.' : 'twill::';
288
289 5
        $view = $partialNamespace . $view . $name;
290
291 5
        $expression = explode(',', $expression);
292 5
        array_shift($expression);
293 5
        $expression = "(" . implode(',', $expression) . ")";
294 5
        if ($expression === "()") {
295 3
            $expression = '([])';
296
        }
297
298 5
        return "<?php echo \$__env->make('{$view}', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render(); ?>";
299
    }
300
301
    /**
302
     * Defines the package additional Blade Directives.
303
     *
304
     * @return void
305
     */
306 59
    private function extendBlade()
307
    {
308 59
        $blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
309
310
        $blade->directive('dd', function ($param) {
311
            return "<?php dd({$param}); ?>";
312 59
        });
313
314
        $blade->directive('dumpData', function ($data) {
315
            return sprintf("<?php (new Symfony\Component\VarDumper\VarDumper)->dump(%s); exit; ?>",
316
                null != $data ? $data : "get_defined_vars()");
317 59
        });
318
319
        $blade->directive('formField', function ($expression) use ($blade) {
0 ignored issues
show
Unused Code introduced by
The import $blade is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
320 5
            return $this->includeView('partials.form._', $expression);
321 59
        });
322
323
        $blade->directive('partialView', function ($expression) use ($blade) {
0 ignored issues
show
Unused Code introduced by
The import $blade is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
324
325 3
            $expressionAsArray = str_getcsv($expression, ',', '\'');
326
327 3
            list($moduleName, $viewName) = $expressionAsArray;
328 3
            $partialNamespace = 'twill::partials';
329
330 3
            $viewModule = "'admin.'.$moduleName.'.{$viewName}'";
331 3
            $viewApplication = "'admin.partials.{$viewName}'";
332 3
            $viewModuleTwill = "'twill::'.$moduleName.'.{$viewName}'";
333 3
            $view = $partialNamespace . "." . $viewName;
334
335 3
            if (!isset($moduleName) || is_null($moduleName)) {
336
                $viewModule = $viewApplication;
337
            }
338
339 3
            $expression = explode(',', $expression);
340 3
            $expression = array_slice($expression, 2);
341 3
            $expression = "(" . implode(',', $expression) . ")";
342 3
            if ($expression === "()") {
343 1
                $expression = '([])';
344
            }
345
346
            return "<?php
347 3
            if( view()->exists($viewModule)) {
348 3
                echo \$__env->make($viewModule, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
349 3
            } elseif( view()->exists($viewApplication)) {
350 3
                echo \$__env->make($viewApplication, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
351 3
            } elseif( view()->exists($viewModuleTwill)) {
352 3
                echo \$__env->make($viewModuleTwill, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
353 3
            } elseif( view()->exists('$view')) {
354 3
                echo \$__env->make('$view', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
355
            }
356
            ?>";
357 59
        });
358
359
        $blade->directive('pushonce', function ($expression) {
360
            list($pushName, $pushSub) = explode(':', trim(substr($expression, 1, -1)));
361
            $key = '__pushonce_' . $pushName . '_' . str_replace('-', '_', $pushSub);
362
            return "<?php if(! isset(\$__env->{$key})): \$__env->{$key} = 1; \$__env->startPush('{$pushName}'); ?>";
363 59
        });
364
365
        $blade->directive('endpushonce', function () {
366
            return '<?php $__env->stopPush(); endif; ?>';
367 59
        });
368 59
    }
369
370
    /**
371
     * Registers the package additional View Composers.
372
     *
373
     * @return void
374
     */
375 59
    private function addViewComposers()
376
    {
377 59
        if (config('twill.enabled.users-management')) {
378 59
            View::composer(['admin.*', 'twill::*'], CurrentUser::class);
379
        }
380
381 59
        if (config('twill.enabled.media-library')) {
382 59
            View::composer('twill::layouts.main', MediasUploaderConfig::class);
383
        }
384
385 59
        if (config('twill.enabled.file-library')) {
386 59
            View::composer('twill::layouts.main', FilesUploaderConfig::class);
387
        }
388
389 59
        View::composer('twill::partials.navigation.*', ActiveNavigation::class);
390
391
        View::composer(['admin.*', 'templates.*', 'twill::*'], function ($view) {
392 50
            $with = array_merge([
393 50
                'renderForBlocks' => false,
394
                'renderForModal' => false,
395 50
            ], $view->getData());
396
397 50
            return $view->with($with);
398 59
        });
399
400 59
        View::composer(['admin.*', 'twill::*'], Localization::class);
401 59
    }
402
403
    /**
404
     * Registers and publishes the package additional translations.
405
     *
406
     * @return void
407
     */
408
    private function registerAndPublishTranslations()
409
    {
410
        $translationPath = __DIR__ . '/../lang';
411
412
        $this->loadTranslationsFrom($translationPath, 'twill');
413
        $this->publishes([$translationPath => resource_path('lang/vendor/twill')], 'translations');
414
    }
415
416
    /**
417
     * Get the version number of Twill.
418
     *
419
     * @return string
420
     */
421 59
    public function version()
422
    {
423 59
        return static::VERSION;
424
    }
425
}
426