Passed
Pull Request — 1.1 (#30)
by
unknown
08:10
created

TwillServiceProvider::publishPublicAssets()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace A17\Twill;
4
5
use A17\Twill\Commands\CreateSuperAdmin;
6
use A17\Twill\Commands\GenerateBlocks;
7
use A17\Twill\Commands\ModuleMake;
8
use A17\Twill\Commands\RefreshLQIP;
9
use A17\Twill\Commands\Setup;
10
use A17\Twill\Http\ViewComposers\ActiveNavigation;
11
use A17\Twill\Http\ViewComposers\CurrentUser;
12
use A17\Twill\Http\ViewComposers\FilesUploaderConfig;
13
use A17\Twill\Http\ViewComposers\MediasUploaderConfig;
14
use A17\Twill\Models\Block;
15
use A17\Twill\Models\File;
16
use A17\Twill\Models\Media;
17
use A17\Twill\Models\User;
18
use A17\Twill\Services\FileLibrary\FileService;
19
use A17\Twill\Services\MediaLibrary\ImageService;
20
use Barryvdh\Debugbar\Facade as Debugbar;
21
use Barryvdh\Debugbar\ServiceProvider as DebugbarServiceProvider;
22
use Cartalyst\Tags\TagsServiceProvider;
23
use Dimsav\Translatable\TranslatableServiceProvider;
24
use Illuminate\Database\Eloquent\Relations\Relation;
25
use Illuminate\Foundation\AliasLoader;
26
use Illuminate\Support\ServiceProvider;
27
use Lsrur\Inspector\Facade\Inspector;
28
use Lsrur\Inspector\InspectorServiceProvider;
29
use Spatie\Activitylog\ActivitylogServiceProvider;
30
use View;
31
32
class TwillServiceProvider extends ServiceProvider
33
{
34
    protected $providers = [
35
        RouteServiceProvider::class,
36
        AuthServiceProvider::class,
37
        ValidationServiceProvider::class,
38
        TranslatableServiceProvider::class,
39
        TagsServiceProvider::class,
40
        ActivitylogServiceProvider::class,
41
    ];
42
43
    public function boot()
44
    {
45
        $this->requireHelpers();
46
47
        $this->publishConfigs();
48
        $this->publishMigrations();
49
50
        $this->registerCommands();
51
52
        $this->registerAndPublishViews();
53
54
        $this->extendBlade();
55
        $this->addViewComposers();
56
    }
57
58
    public function register()
59
    {
60
        $this->mergeConfigs();
61
62
        $this->registerProviders();
63
        $this->registerAliases();
64
65
        Relation::morphMap([
66
            'users' => User::class,
67
            'media' => Media::class,
68
            'files' => File::class,
69
            'blocks' => Block::class,
70
        ]);
71
72
        config(['twill.version' => trim(file_get_contents(__DIR__ . '/../VERSION'))]);
73
    }
74
75
    public function provides()
76
    {
77
        return ['Illuminate\Contracts\Debug\ExceptionHandler'];
78
    }
79
80
    private function registerProviders()
81
    {
82
        foreach ($this->providers as $provider) {
83
            $this->app->register($provider);
84
        }
85
86
        if ($this->app->environment('development', 'local', 'staging')) {
87
            if (config('twill.debug.use_inspector', false)) {
88
                $this->app->register(InspectorServiceProvider::class);
89
            } else {
90
                $this->app->register(DebugbarServiceProvider::class);
91
            }
92
        }
93
94
        if (config('twill.enabled.media-library')) {
95
            $this->app->singleton('imageService', function () {
96
                return $this->app->make(config('twill.media_library.image_service'));
97
            });
98
        }
99
100
        if (config('twill.enabled.file-library')) {
101
            $this->app->singleton('fileService', function () {
102
                return $this->app->make(config('twill.file_library.file_service'));
103
            });
104
        }
105
    }
106
107
    private function registerAliases()
108
    {
109
        $loader = AliasLoader::getInstance();
110
111
        if (config('twill.debug.use_inspector', false)) {
112
            $loader->alias('Inspector', Inspector::class);
113
        } else {
114
            $loader->alias('Debugbar', Debugbar::class);
115
        }
116
117
        if (config('twill.enabled.media-library')) {
118
            $loader->alias('ImageService', ImageService::class);
119
        }
120
121
        if (config('twill.enabled.file-library')) {
122
            $loader->alias('FileService', FileService::class);
123
        }
124
125
    }
126
127
    private function publishConfigs()
128
    {
129
        if (config('twill.enabled.users-management')) {
130
            config(['auth.providers.users' => require __DIR__ . '/../config/auth.php']);
131
            config(['mail.markdown.paths' => array_merge(
132
                [__DIR__ . '/../views/emails'],
133
                config('mail.markdown.paths')
134
            )]);
135
        }
136
137
        config(['activitylog.enabled' => config('twill.enabled.dashboard')]);
138
        config(['activitylog.subject_returns_soft_deleted_models' => true]);
139
140
        config(['analytics.service_account_credentials_json' => config('twill.dashboard.analytics.service_account_credentials_json', storage_path('app/analytics/service-account-credentials.json'))]);
141
142
        $this->publishes([__DIR__ . '/../config/twill-publish.php' => config_path('twill.php')], 'config');
143
        $this->publishes([__DIR__ . '/../config/twill-navigation.php' => config_path('twill-navigation.php')], 'config');
144
    }
145
146
    private function mergeConfigs()
147
    {
148
        $this->mergeConfigFrom(__DIR__ . '/../config/twill.php', 'twill');
149
        $this->mergeConfigFrom(__DIR__ . '/../config/disks.php', 'filesystems.disks');
150
        $this->mergeConfigFrom(__DIR__ . '/../config/frontend.php', 'twill.frontend');
151
        $this->mergeConfigFrom(__DIR__ . '/../config/debug.php', 'twill.debug');
152
        $this->mergeConfigFrom(__DIR__ . '/../config/seo.php', 'twill.seo');
153
        $this->mergeConfigFrom(__DIR__ . '/../config/blocks.php', 'twill.block_editor');
154
        $this->mergeConfigFrom(__DIR__ . '/../config/enabled.php', 'twill.enabled');
155
        $this->mergeConfigFrom(__DIR__ . '/../config/imgix.php', 'twill.imgix');
156
        $this->mergeConfigFrom(__DIR__ . '/../config/media-library.php', 'twill.media_library');
157
        $this->mergeConfigFrom(__DIR__ . '/../config/file-library.php', 'twill.file_library');
158
        $this->mergeConfigFrom(__DIR__ . '/../config/cloudfront.php', 'services');
159
    }
160
161
    private function publishMigrations()
162
    {
163
        $migrations = ['CreateTagsTables', 'CreateBlocksTable'];
164
165
        $optionalMigrations = [
166
            'CreateUsersTables' => 'users-management',
167
            'CreateFilesTables' => 'file-library',
168
            'CreateMediasTables' => 'media-library',
169
            'CreateFeaturesTable' => 'buckets',
170
        ];
171
172
        if ($this->app->runningInConsole()) {
173
            foreach ($migrations as $migration) {
174
                $this->publishMigration($migration);
175
            }
176
177
            foreach ($optionalMigrations as $migration => $feature) {
178
                if (config('twill.enabled.' . $feature)) {
179
                    $this->publishMigration($migration);
180
                }
181
            }
182
        }
183
    }
184
185
    private function publishMigration($migration)
186
    {
187
        if (!class_exists($migration)) {
188
            $timestamp = date('Y_m_d_His', time());
189
            $this->publishes([
190
                __DIR__ . '/../migrations/' . snake_case($migration) . '.php' => database_path('migrations/' . $timestamp . '_' . snake_case($migration) . '.php'),
191
            ], 'migrations');
192
        }
193
    }
194
195
    private function registerAndPublishViews()
196
    {
197
        $viewPath = __DIR__ . '/../views';
198
199
        $this->loadViewsFrom($viewPath, 'twill');
200
        $this->publishes([$viewPath => resource_path('views/vendor/twill')], 'views');
201
    }
202
203
    private function registerCommands()
204
    {
205
        $this->commands([
206
            Setup::class,
207
            ModuleMake::class,
208
            CreateSuperAdmin::class,
209
            RefreshLQIP::class,
210
            GenerateBlocks::class,
211
        ]);
212
    }
213
214
    private function requireHelpers()
215
    {
216
        require_once __DIR__ . '/Helpers/routes_helpers.php';
217
        require_once __DIR__ . '/Helpers/i18n_helpers.php';
218
        require_once __DIR__ . '/Helpers/media_library_helpers.php';
219
        require_once __DIR__ . '/Helpers/frontend_helpers.php';
220
        require_once __DIR__ . '/Helpers/migrations_helpers.php';
221
        require_once __DIR__ . '/Helpers/helpers.php';
222
    }
223
224
225
    private function includeView($view, $expression)
226
    {
227
        list($name) = str_getcsv($expression, ',', '\'');
228
229
        $partialNamespace = view()->exists('admin.' . $view . $name) ? 'admin.' : 'twill::';
230
231
        $view = $partialNamespace . $view . $name;
232
233
        $expression = explode(',', $expression);
234
        array_shift($expression);
235
        $expression = "(" . implode(',', $expression) . ")";
236
        if ($expression === "()") {
237
            $expression = '([])';
238
        }
239
        return "<?php echo \$__env->make('{$view}', array_except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render(); ?>";
240
    }
241
242
    private function extendBlade()
243
    {
244
        $blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
245
246
        $blade->directive('dd', function ($param) {
247
            return "<?php dd({$param}); ?>";
248
        });
249
250
        $blade->directive('dumpData', function ($data) {
251
            return sprintf("<?php (new Illuminate\Support\Debug\Dumper)->dump(%s); exit; ?>",
252
                null != $data ? $data : "get_defined_vars()");
253
        });
254
255
        $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...
256
            return $this->includeView('partials.form._', $expression);
257
        });
258
259
        $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...
260
261
            $expressionAsArray = str_getcsv($expression, ',', '\'');
262
263
            list($moduleName, $viewName) = $expressionAsArray;
264
            $partialNamespace = 'twill::partials';
265
266
            $viewModule = "'admin.'.$moduleName.'.{$viewName}'";
267
            $viewApplication = "'admin.partials.{$viewName}'";
268
            $viewModuleTwill = "'twill::'.$moduleName.'.{$viewName}'";
269
            $view = $partialNamespace . "." . $viewName;
270
271
            if (!isset($moduleName) || is_null($moduleName)) {
272
                $viewModule = $viewApplication;
273
            }
274
275
            $expression = explode(',', $expression);
276
            $expression = array_slice($expression, 2);
277
            $expression = "(" . implode(',', $expression) . ")";
278
            if ($expression === "()") {
279
                $expression = '([])';
280
            }
281
282
            return "<?php
283
            if( view()->exists($viewModule)) {
284
                echo \$__env->make($viewModule, array_except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
285
            } elseif( view()->exists($viewApplication)) {
286
                echo \$__env->make($viewApplication, array_except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
287
            } elseif( view()->exists($viewModuleTwill)) {
288
                echo \$__env->make($viewModuleTwill, array_except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
289
            } elseif( view()->exists('$view')) {
290
                echo \$__env->make('$view', array_except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
291
            }
292
            ?>";
293
        });
294
295
        $blade->directive('pushonce', function ($expression) {
296
            list($pushName, $pushSub) = explode(':', trim(substr($expression, 1, -1)));
297
            $key = '__pushonce_' . $pushName . '_' . str_replace('-', '_', $pushSub);
298
            return "<?php if(! isset(\$__env->{$key})): \$__env->{$key} = 1; \$__env->startPush('{$pushName}'); ?>";
299
        });
300
301
        $blade->directive('endpushonce', function () {
302
            return '<?php $__env->stopPush(); endif; ?>';
303
        });
304
    }
305
306
    private function addViewComposers()
307
    {
308
        if (config('twill.enabled.users-management')) {
309
            View::composer(['admin.*', 'twill::*'], CurrentUser::class);
0 ignored issues
show
Bug introduced by
A17\Twill\Http\ViewComposers\CurrentUser::class of type string is incompatible with the type Closure expected by parameter $| of Illuminate\Support\Facades\View::composer(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

309
            View::composer(['admin.*', 'twill::*'], /** @scrutinizer ignore-type */ CurrentUser::class);
Loading history...
310
        }
311
312
        if (config('twill.enabled.media-library')) {
313
            View::composer('twill::layouts.main', MediasUploaderConfig::class);
314
        }
315
316
        if (config('twill.enabled.file-library')) {
317
            View::composer('twill::layouts.main', FilesUploaderConfig::class);
318
        }
319
320
        View::composer('twill::partials.navigation.*', ActiveNavigation::class);
321
322
        View::composer(['admin.*', 'templates.*', 'twill::*'], function ($view) {
323
            $with = array_merge([
324
                'renderForBlocks' => false,
325
                'renderForModal' => false,
326
            ], $view->getData());
327
328
            return $view->with($with);
329
        });
330
331
    }
332
333
    private function registerAndPublishTranslations()
334
    {
335
        $translationPath = __DIR__ . '/../lang';
336
337
        $this->loadTranslationsFrom($translationPath, 'twill');
338
        $this->publishes([$translationPath => resource_path('lang/vendor/twill')], 'translations');
339
    }
340
}
341