Passed
Push — dependabot/npm_and_yarn/docs/w... ( a770a9...3a5b31 )
by
unknown
07:47
created

TwillServiceProvider::addViewComposers()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 14
nc 8
nop 0
dl 0
loc 26
ccs 14
cts 14
cp 1
crap 4
rs 9.7998
c 1
b 0
f 0
1
<?php
2
3
namespace A17\Twill;
4
5
use A17\Twill\Commands\BlockMake;
6
use A17\Twill\Commands\Build;
7
use A17\Twill\Commands\CreateSuperAdmin;
8
use A17\Twill\Commands\Dev;
9
use A17\Twill\Commands\GenerateBlocks;
10
use A17\Twill\Commands\Install;
11
use A17\Twill\Commands\ListBlocks;
12
use A17\Twill\Commands\ListIcons;
13
use A17\Twill\Commands\ModuleMake;
14
use A17\Twill\Commands\ModuleMakeDeprecated;
15
use A17\Twill\Commands\RefreshLQIP;
16
use A17\Twill\Commands\Update;
17
use A17\Twill\Commands\SyncLang;
18
use A17\Twill\Http\ViewComposers\ActiveNavigation;
19
use A17\Twill\Http\ViewComposers\CurrentUser;
20
use A17\Twill\Http\ViewComposers\FilesUploaderConfig;
21
use A17\Twill\Http\ViewComposers\Localization;
22
use A17\Twill\Http\ViewComposers\MediasUploaderConfig;
23
use A17\Twill\Models\Block;
24
use A17\Twill\Models\File;
25
use A17\Twill\Models\Media;
26
use A17\Twill\Models\User;
27
use A17\Twill\Services\FileLibrary\FileService;
28
use A17\Twill\Services\MediaLibrary\ImageService;
29
use Astrotomic\Translatable\TranslatableServiceProvider;
30
use Cartalyst\Tags\TagsServiceProvider;
31
use Illuminate\Database\Eloquent\Relations\Relation;
32
use Illuminate\Foundation\AliasLoader;
33
use Illuminate\Support\Facades\View;
34
use Illuminate\Support\ServiceProvider;
35
use Illuminate\Support\Str;
36
use Spatie\Activitylog\ActivitylogServiceProvider;
37
38
class TwillServiceProvider extends ServiceProvider
39
{
40
41
    /**
42
     * The Twill version.
43
     *
44
     * @var string
45
     */
46
    const VERSION = '2.1.0';
47
48
    /**
49
     * Service providers to be registered.
50
     *
51
     * @var string[]
52
     */
53
    protected $providers = [
54
        RouteServiceProvider::class,
55
        AuthServiceProvider::class,
56
        ValidationServiceProvider::class,
57
        TranslatableServiceProvider::class,
58
        TagsServiceProvider::class,
59
        ActivitylogServiceProvider::class,
60
    ];
61
62
    private $migrationsCounter = 0;
0 ignored issues
show
introduced by
The private property $migrationsCounter is not used, and could be removed.
Loading history...
63
64
    /**
65
     * Bootstraps the package services.
66
     *
67
     * @return void
68
     */
69 73
    public function boot()
70
    {
71 73
        $this->requireHelpers();
72
73 73
        $this->publishConfigs();
74 73
        $this->publishMigrations();
75 73
        $this->publishAssets();
76
77 73
        $this->registerCommands();
78
79 73
        $this->registerAndPublishViews();
80 73
        $this->registerAndPublishTranslations();
81
82 73
        $this->extendBlade();
83 73
        $this->addViewComposers();
84 73
    }
85
86
    /**
87
     * @return void
88
     */
89 73
    private function requireHelpers()
90
    {
91 73
        require_once __DIR__ . '/Helpers/routes_helpers.php';
92 73
        require_once __DIR__ . '/Helpers/i18n_helpers.php';
93 73
        require_once __DIR__ . '/Helpers/media_library_helpers.php';
94 73
        require_once __DIR__ . '/Helpers/frontend_helpers.php';
95 73
        require_once __DIR__ . '/Helpers/migrations_helpers.php';
96 73
        require_once __DIR__ . '/Helpers/helpers.php';
97 73
    }
98
99
    /**
100
     * Registers the package services.
101
     *
102
     * @return void
103
     */
104 73
    public function register()
105
    {
106 73
        $this->mergeConfigs();
107
108 73
        $this->registerProviders();
109 73
        $this->registerAliases();
110
111 73
        Relation::morphMap([
112 73
            'users' => User::class,
113
            'media' => Media::class,
114
            'files' => File::class,
115
            'blocks' => Block::class,
116
        ]);
117
118 73
        config(['twill.version' => $this->version()]);
119 73
    }
120
121
    /**
122
     * Registers the package service providers.
123
     *
124
     * @return void
125
     */
126 73
    private function registerProviders()
127
    {
128 73
        foreach ($this->providers as $provider) {
129 73
            $this->app->register($provider);
130
        }
131
132 73
        if (config('twill.enabled.media-library')) {
133
            $this->app->singleton('imageService', function () {
134 8
                return $this->app->make(config('twill.media_library.image_service'));
135 73
            });
136
        }
137
138 73
        if (config('twill.enabled.file-library')) {
139
            $this->app->singleton('fileService', function () {
140 3
                return $this->app->make(config('twill.file_library.file_service'));
141 73
            });
142
        }
143 73
    }
144
145
    /**
146
     * Registers the package facade aliases.
147
     *
148
     * @return void
149
     */
150 73
    private function registerAliases()
151
    {
152 73
        $loader = AliasLoader::getInstance();
153
154 73
        if (config('twill.enabled.media-library')) {
155 73
            $loader->alias('ImageService', ImageService::class);
156
        }
157
158 73
        if (config('twill.enabled.file-library')) {
159 73
            $loader->alias('FileService', FileService::class);
160
        }
161
162 73
    }
163
164
    /**
165
     * Defines the package configuration files for publishing.
166
     *
167
     * @return void
168
     */
169 73
    private function publishConfigs()
170
    {
171 73
        if (config('twill.enabled.users-management')) {
172 73
            config(['auth.providers.twill_users' => [
173 73
                'driver' => 'eloquent',
174
                'model' => User::class,
175
            ]]);
176
177 73
            config(['auth.guards.twill_users' => [
178 73
                'driver' => 'session',
179
                'provider' => 'twill_users',
180
            ]]);
181
182 73
            config(['auth.passwords.twill_users' => [
183 73
                'provider' => 'twill_users',
184 73
                'table' => config('twill.password_resets_table', 'twill_password_resets'),
185 73
                'expire' => 60,
186
            ]]);
187
        }
188
189 73
        config(['activitylog.enabled' => config('twill.enabled.dashboard') ? true : config('twill.enabled.activitylog')]);
190 73
        config(['activitylog.subject_returns_soft_deleted_models' => true]);
191
192 73
        config(['analytics.service_account_credentials_json' => config('twill.dashboard.analytics.service_account_credentials_json', storage_path('app/analytics/service-account-credentials.json'))]);
193
194 73
        $this->publishes([__DIR__ . '/../config/twill-publish.php' => config_path('twill.php')], 'config');
195 73
        $this->publishes([__DIR__ . '/../config/twill-navigation.php' => config_path('twill-navigation.php')], 'config');
196 73
        $this->publishes([__DIR__ . '/../config/translatable.php' => config_path('translatable.php')], 'config');
197 73
    }
198
199
    /**
200
     * Merges the package configuration files into the given configuration namespaces.
201
     *
202
     * @return void
203
     */
204 73
    private function mergeConfigs()
205
    {
206 73
        $this->mergeConfigFrom(__DIR__ . '/../config/twill.php', 'twill');
207 73
        $this->mergeConfigFrom(__DIR__ . '/../config/frontend.php', 'twill.frontend');
208 73
        $this->mergeConfigFrom(__DIR__ . '/../config/debug.php', 'twill.debug');
209 73
        $this->mergeConfigFrom(__DIR__ . '/../config/seo.php', 'twill.seo');
210 73
        $this->mergeConfigFrom(__DIR__ . '/../config/blocks.php', 'twill.block_editor');
211 73
        $this->mergeConfigFrom(__DIR__ . '/../config/enabled.php', 'twill.enabled');
212 73
        $this->mergeConfigFrom(__DIR__ . '/../config/file-library.php', 'twill.file_library');
213 73
        $this->mergeConfigFrom(__DIR__ . '/../config/media-library.php', 'twill.media_library');
214 73
        $this->mergeConfigFrom(__DIR__ . '/../config/imgix.php', 'twill.imgix');
215 73
        $this->mergeConfigFrom(__DIR__ . '/../config/glide.php', 'twill.glide');
216 73
        $this->mergeConfigFrom(__DIR__ . '/../config/dashboard.php', 'twill.dashboard');
217 73
        $this->mergeConfigFrom(__DIR__ . '/../config/oauth.php', 'twill.oauth');
218 73
        $this->mergeConfigFrom(__DIR__ . '/../config/disks.php', 'filesystems.disks');
219
220 73
        if (config('twill.media_library.endpoint_type') === 'local'
221 73
            && config('twill.media_library.disk') === 'twill_media_library') {
222 73
            $this->setLocalDiskUrl('media');
223
        }
224
225 73
        if (config('twill.file_library.endpoint_type') === 'local'
226 73
            && config('twill.file_library.disk') === 'twill_file_library') {
227 73
            $this->setLocalDiskUrl('file');
228
        }
229
230 73
        $this->mergeConfigFrom(__DIR__ . '/../config/services.php', 'services');
231 73
    }
232
233 73
    private function setLocalDiskUrl($type)
234
    {
235 73
        config([
236 73
            'filesystems.disks.twill_' . $type . '_library.url' => request()->getScheme()
237 73
            . '://'
238 73
            . str_replace(['http://', 'https://'], '', config('app.url'))
239 73
            . '/storage/'
240 73
            . trim(config('twill.' . $type . '_library.local_path'), '/ '),
241
        ]);
242 73
    }
243
244 73
    private function publishMigrations()
245
    {
246 73
        if (config('twill.load_default_migrations', true)) {
247 73
            $this->loadMigrationsFrom(__DIR__ . '/../migrations/default');
248
        }
249
250 73
        $this->publishes([
251 73
            __DIR__ . '/../migrations/default' => database_path('migrations'),
252 73
        ], 'migrations');
253
254 73
        $this->publishOptionalMigration('users-2fa');
255 73
        $this->publishOptionalMigration('users-oauth');
256 73
    }
257
258 73
    private function publishOptionalMigration($feature)
259
    {
260 73
        if (config('twill.enabled.' . $feature, false)) {
261 69
            $this->loadMigrationsFrom(__DIR__ . '/../migrations/optional/' . $feature);
262
263 69
            $this->publishes([
264 69
                __DIR__ . '/../migrations/optional/' . $feature => database_path('migrations'),
265 69
            ], 'migrations');
266
        }
267 73
    }
268
269
    /**
270
     * @return void
271
     */
272 73
    private function publishAssets()
273
    {
274 73
        $this->publishes([
275 73
            __DIR__ . '/../dist' => public_path(),
276 73
        ], 'assets');
277 73
    }
278
279
    /**
280
     * @return void
281
     */
282 73
    private function registerAndPublishViews()
283
    {
284 73
        $viewPath = __DIR__ . '/../views';
285
286 73
        $this->loadViewsFrom($viewPath, 'twill');
287 73
        $this->publishes([$viewPath => resource_path('views/vendor/twill')], 'views');
288 73
    }
289
290
    /**
291
     * @return void
292
     */
293 73
    private function registerCommands()
294
    {
295 73
        $this->commands([
296 73
            Install::class,
297
            ModuleMake::class,
298
            ModuleMakeDeprecated::class,
299
            BlockMake::class,
300
            ListIcons::class,
301
            ListBlocks::class,
302
            CreateSuperAdmin::class,
303
            RefreshLQIP::class,
304
            GenerateBlocks::class,
305
            Build::class,
306
            Update::class,
307
            Dev::class,
308
            SyncLang::class,
309
        ]);
310 73
    }
311
312
    /**
313
     * @param string $view
314
     * @param string $expression
315
     * @return string
316
     */
317 5
    private function includeView($view, $expression)
318
    {
319 5
        list($name) = str_getcsv($expression, ',', '\'');
320
321 5
        $partialNamespace = view()->exists('admin.' . $view . $name) ? 'admin.' : 'twill::';
322
323 5
        $view = $partialNamespace . $view . $name;
324
325 5
        $expression = explode(',', $expression);
326 5
        array_shift($expression);
327 5
        $expression = "(" . implode(',', $expression) . ")";
328 5
        if ($expression === "()") {
329 4
            $expression = '([])';
330
        }
331
332 5
        return "<?php echo \$__env->make('{$view}', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render(); ?>";
333
    }
334
335
    /**
336
     * Defines the package additional Blade Directives.
337
     *
338
     * @return void
339
     */
340 73
    private function extendBlade()
341
    {
342 73
        $blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
343
344
        $blade->directive('dd', function ($param) {
345
            return "<?php dd({$param}); ?>";
346 73
        });
347
348
        $blade->directive('dumpData', function ($data) {
349
            return sprintf("<?php (new Symfony\Component\VarDumper\VarDumper)->dump(%s); exit; ?>",
350
                null != $data ? $data : "get_defined_vars()");
351 73
        });
352
353
        $blade->directive('formField', function ($expression) {
354 5
            return $this->includeView('partials.form._', $expression);
355 73
        });
356
357
        $blade->directive('partialView', function ($expression) {
358
359 3
            $expressionAsArray = str_getcsv($expression, ',', '\'');
360
361 3
            list($moduleName, $viewName) = $expressionAsArray;
362 3
            $partialNamespace = 'twill::partials';
363
364 3
            $viewModule = "'admin.'.$moduleName.'.{$viewName}'";
365 3
            $viewApplication = "'admin.partials.{$viewName}'";
366 3
            $viewModuleTwill = "'twill::'.$moduleName.'.{$viewName}'";
367 3
            $view = $partialNamespace . "." . $viewName;
368
369 3
            if (!isset($moduleName) || is_null($moduleName)) {
370
                $viewModule = $viewApplication;
371
            }
372
373 3
            $expression = explode(',', $expression);
374 3
            $expression = array_slice($expression, 2);
375 3
            $expression = "(" . implode(',', $expression) . ")";
376 3
            if ($expression === "()") {
377 2
                $expression = '([])';
378
            }
379
380 3
            return "<?php
381 3
            if( view()->exists($viewModule)) {
382 3
                echo \$__env->make($viewModule, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
383 3
            } elseif( view()->exists($viewApplication)) {
384 3
                echo \$__env->make($viewApplication, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
385 3
            } elseif( view()->exists($viewModuleTwill)) {
386 3
                echo \$__env->make($viewModuleTwill, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
387 3
            } elseif( view()->exists('$view')) {
388 3
                echo \$__env->make('$view', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
389
            }
390
            ?>";
391 73
        });
392
393
        $blade->directive('pushonce', function ($expression) {
394 1
            list($pushName, $pushSub) = explode(':', trim(substr($expression, 1, -1)));
395 1
            $key = '__pushonce_' . $pushName . '_' . str_replace('-', '_', $pushSub);
396 1
            return "<?php if(! isset(\$__env->{$key})): \$__env->{$key} = 1; \$__env->startPush('{$pushName}'); ?>";
397 73
        });
398
399
        $blade->directive('endpushonce', function () {
400 1
            return '<?php $__env->stopPush(); endif; ?>';
401 73
        });
402
403 73
        $blade->component('twill::partials.form.utils._fieldset', 'formFieldset');
404 73
        $blade->component('twill::partials.form.utils._columns', 'formColumns');
405 73
        $blade->component('twill::partials.form.utils._collapsed_fields', 'formCollapsedFields');
406 73
        $blade->component('twill::partials.form.utils._connected_fields', 'formConnectedFields');
407 73
        $blade->component('twill::partials.form.utils._inline_checkboxes', 'formInlineCheckboxes');
408
409 73
        if (method_exists($blade, 'aliasComponent')) {
410 73
            $blade->aliasComponent('twill::partials.form.utils._fieldset', 'formFieldset');
411 73
            $blade->aliasComponent('twill::partials.form.utils._columns', 'formColumns');
412 73
            $blade->aliasComponent('twill::partials.form.utils._collapsed_fields', 'formCollapsedFields');
413 73
            $blade->aliasComponent('twill::partials.form.utils._connected_fields', 'formConnectedFields');
414 73
            $blade->aliasComponent('twill::partials.form.utils._inline_checkboxes', 'formInlineCheckboxes');
415
        }
416
417 73
    }
418
419
    /**
420
     * Registers the package additional View Composers.
421
     *
422
     * @return void
423
     */
424 73
    private function addViewComposers()
425
    {
426 73
        if (config('twill.enabled.users-management')) {
427 73
            View::composer(['admin.*', 'twill::*'], CurrentUser::class);
428
        }
429
430 73
        if (config('twill.enabled.media-library')) {
431 73
            View::composer('twill::layouts.main', MediasUploaderConfig::class);
432
        }
433
434 73
        if (config('twill.enabled.file-library')) {
435 73
            View::composer('twill::layouts.main', FilesUploaderConfig::class);
436
        }
437
438 73
        View::composer('twill::partials.navigation.*', ActiveNavigation::class);
439
440
        View::composer(['admin.*', 'templates.*', 'twill::*'], function ($view) {
441 52
            $with = array_merge([
442 52
                'renderForBlocks' => false,
443
                'renderForModal' => false,
444 52
            ], $view->getData());
445
446 52
            return $view->with($with);
447 73
        });
448
449 73
        View::composer(['admin.*', 'twill::*'], Localization::class);
450 73
    }
451
452
    /**
453
     * Registers and publishes the package additional translations.
454
     *
455
     * @return void
456
     */
457 73
    private function registerAndPublishTranslations()
458
    {
459 73
        $translationPath = __DIR__ . '/../lang';
460
461 73
        $this->loadTranslationsFrom($translationPath, 'twill');
462 73
        $this->publishes([$translationPath => resource_path('lang/vendor/twill')], 'translations');
463 73
    }
464
465
    /**
466
     * Get the version number of Twill.
467
     *
468
     * @return string
469
     */
470 73
    public function version()
471
    {
472 73
        return static::VERSION;
473
    }
474
}
475