Passed
Push — 2.x ( fc5b16...8082d7 )
by Quentin
06:25
created

TwillServiceProvider::setLocalDiskUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

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