Passed
Pull Request — 2.x (#597)
by Antonio Carlos
05:31
created

TwillServiceProvider::extendBlade()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 68
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 34
CRAP Score 5.2291

Importance

Changes 0
Metric Value
cc 5
eloc 43
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 68
ccs 34
cts 43
cp 0.7907
crap 5.2291
rs 8.9208

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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