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

TwillServiceProvider::extendBlade()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 68
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 39
CRAP Score 5.0201

Importance

Changes 0
Metric Value
cc 5
eloc 43
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 68
ccs 39
cts 43
cp 0.907
crap 5.0201
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 70
    public function boot()
67
    {
68 70
        $this->requireHelpers();
69
70 70
        $this->publishConfigs();
71 70
        $this->publishMigrations();
72 70
        $this->publishAssets();
73
74 70
        $this->registerCommands();
75
76 70
        $this->registerAndPublishViews();
77 70
        $this->registerAndPublishTranslations();
78
79 70
        $this->extendBlade();
80 70
        $this->addViewComposers();
81 70
    }
82
83
    /**
84
     * @return void
85
     */
86 70
    private function requireHelpers()
87
    {
88 70
        require_once __DIR__ . '/Helpers/routes_helpers.php';
89 70
        require_once __DIR__ . '/Helpers/i18n_helpers.php';
90 70
        require_once __DIR__ . '/Helpers/media_library_helpers.php';
91 70
        require_once __DIR__ . '/Helpers/frontend_helpers.php';
92 70
        require_once __DIR__ . '/Helpers/migrations_helpers.php';
93 70
        require_once __DIR__ . '/Helpers/helpers.php';
94 70
    }
95
96
    /**
97
     * Registers the package services.
98
     *
99
     * @return void
100
     */
101 70
    public function register()
102
    {
103 70
        $this->mergeConfigs();
104
105 70
        $this->registerProviders();
106 70
        $this->registerAliases();
107
108 70
        Relation::morphMap([
109 70
            'users' => User::class,
110
            'media' => Media::class,
111
            'files' => File::class,
112
            'blocks' => Block::class,
113
        ]);
114
115 70
        config(['twill.version' => $this->version()]);
116 70
    }
117
118
    /**
119
     * Registers the package service providers.
120
     *
121
     * @return void
122
     */
123 70
    private function registerProviders()
124
    {
125 70
        foreach ($this->providers as $provider) {
126 70
            $this->app->register($provider);
127
        }
128
129 70
        if (config('twill.enabled.media-library')) {
130
            $this->app->singleton('imageService', function () {
131 7
                return $this->app->make(config('twill.media_library.image_service'));
132 70
            });
133
        }
134
135 70
        if (config('twill.enabled.file-library')) {
136
            $this->app->singleton('fileService', function () {
137 3
                return $this->app->make(config('twill.file_library.file_service'));
138 70
            });
139
        }
140 70
    }
141
142
    /**
143
     * Registers the package facade aliases.
144
     *
145
     * @return void
146
     */
147 70
    private function registerAliases()
148
    {
149 70
        $loader = AliasLoader::getInstance();
150
151 70
        if (config('twill.enabled.media-library')) {
152 70
            $loader->alias('ImageService', ImageService::class);
153
        }
154
155 70
        if (config('twill.enabled.file-library')) {
156 70
            $loader->alias('FileService', FileService::class);
157
        }
158
159 70
    }
160
161
    /**
162
     * Defines the package configuration files for publishing.
163
     *
164
     * @return void
165
     */
166 70
    private function publishConfigs()
167
    {
168 70
        if (config('twill.enabled.users-management')) {
169 70
            config(['auth.providers.twill_users' => [
170 70
                'driver' => 'eloquent',
171
                'model' => User::class,
172
            ]]);
173
174 70
            config(['auth.guards.twill_users' => [
175 70
                'driver' => 'session',
176
                'provider' => 'twill_users',
177
            ]]);
178
179 70
            config(['auth.passwords.twill_users' => [
180 70
                'provider' => 'twill_users',
181 70
                'table' => config('twill.password_resets_table', 'twill_password_resets'),
182 70
                'expire' => 60,
183
            ]]);
184
        }
185
186 70
        config(['activitylog.enabled' => config('twill.enabled.dashboard') ? true : config('twill.enabled.activitylog')]);
187 70
        config(['activitylog.subject_returns_soft_deleted_models' => true]);
188
189 70
        config(['analytics.service_account_credentials_json' => config('twill.dashboard.analytics.service_account_credentials_json', storage_path('app/analytics/service-account-credentials.json'))]);
190
191 70
        $this->publishes([__DIR__ . '/../config/twill-publish.php' => config_path('twill.php')], 'config');
192 70
        $this->publishes([__DIR__ . '/../config/twill-navigation.php' => config_path('twill-navigation.php')], 'config');
193 70
        $this->publishes([__DIR__ . '/../config/translatable.php' => config_path('translatable.php')], 'config');
194 70
    }
195
196
    /**
197
     * Merges the package configuration files into the given configuration namespaces.
198
     *
199
     * @return void
200
     */
201 70
    private function mergeConfigs()
202
    {
203 70
        $this->mergeConfigFrom(__DIR__ . '/../config/twill.php', 'twill');
204 70
        $this->mergeConfigFrom(__DIR__ . '/../config/frontend.php', 'twill.frontend');
205 70
        $this->mergeConfigFrom(__DIR__ . '/../config/debug.php', 'twill.debug');
206 70
        $this->mergeConfigFrom(__DIR__ . '/../config/seo.php', 'twill.seo');
207 70
        $this->mergeConfigFrom(__DIR__ . '/../config/blocks.php', 'twill.block_editor');
208 70
        $this->mergeConfigFrom(__DIR__ . '/../config/enabled.php', 'twill.enabled');
209 70
        $this->mergeConfigFrom(__DIR__ . '/../config/file-library.php', 'twill.file_library');
210 70
        $this->mergeConfigFrom(__DIR__ . '/../config/media-library.php', 'twill.media_library');
211 70
        $this->mergeConfigFrom(__DIR__ . '/../config/imgix.php', 'twill.imgix');
212 70
        $this->mergeConfigFrom(__DIR__ . '/../config/glide.php', 'twill.glide');
213 70
        $this->mergeConfigFrom(__DIR__ . '/../config/dashboard.php', 'twill.dashboard');
214 70
        $this->mergeConfigFrom(__DIR__ . '/../config/oauth.php', 'twill.oauth');
215 70
        $this->mergeConfigFrom(__DIR__ . '/../config/disks.php', 'filesystems.disks');
216 70
        $this->mergeConfigFrom(__DIR__ . '/../config/services.php', 'services');
217 70
    }
218
219 70
    private function publishMigrations()
220
    {
221 70
        if (config('twill.load_default_migrations', true)) {
222 70
            $this->loadMigrationsFrom(__DIR__ . '/../migrations/default');
223
        }
224
225 70
        $this->publishes([
226 70
            __DIR__ . '/../migrations/default' => database_path('migrations'),
227 70
        ], 'migrations');
228
229 70
        $this->publishOptionalMigration('users-2fa');
230 70
        $this->publishOptionalMigration('users-oauth');
231 70
    }
232
233 70
    private function publishOptionalMigration($feature)
234
    {
235 70
        if (config('twill.enabled.' . $feature, false)) {
236 66
            $this->loadMigrationsFrom(__DIR__ . '/../migrations/optional/' . $feature);
237
238 66
            $this->publishes([
239 66
                __DIR__ . '/../migrations/optional/' . $feature => database_path('migrations'),
240 66
            ], 'migrations');
241
        }
242 70
    }
243
244
    /**
245
     * @return void
246
     */
247 70
    private function publishAssets()
248
    {
249 70
        $this->publishes([
250 70
            __DIR__ . '/../dist' => public_path(),
251 70
        ], 'assets');
252 70
    }
253
254
    /**
255
     * @return void
256
     */
257 70
    private function registerAndPublishViews()
258
    {
259 70
        $viewPath = __DIR__ . '/../views';
260
261 70
        $this->loadViewsFrom($viewPath, 'twill');
262 70
        $this->publishes([$viewPath => resource_path('views/vendor/twill')], 'views');
263 70
    }
264
265
    /**
266
     * @return void
267
     */
268 70
    private function registerCommands()
269
    {
270 70
        $this->commands([
271 70
            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 70
    }
283
284
    /**
285
     * @param string $view
286
     * @param string $expression
287
     * @return string
288
     */
289 4
    private function includeView($view, $expression)
290
    {
291 4
        list($name) = str_getcsv($expression, ',', '\'');
292
293 4
        $partialNamespace = view()->exists('admin.' . $view . $name) ? 'admin.' : 'twill::';
294
295 4
        $view = $partialNamespace . $view . $name;
296
297 4
        $expression = explode(',', $expression);
298 4
        array_shift($expression);
299 4
        $expression = "(" . implode(',', $expression) . ")";
300 4
        if ($expression === "()") {
301 3
            $expression = '([])';
302
        }
303
304 4
        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 70
    private function extendBlade()
313
    {
314 70
        $blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
315
316
        $blade->directive('dd', function ($param) {
317
            return "<?php dd({$param}); ?>";
318 70
        });
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 70
        });
324
325
        $blade->directive('formField', function ($expression) {
326 4
            return $this->includeView('partials.form._', $expression);
327 70
        });
328
329
        $blade->directive('partialView', function ($expression) {
330
331 3
            $expressionAsArray = str_getcsv($expression, ',', '\'');
332
333 3
            list($moduleName, $viewName) = $expressionAsArray;
334 3
            $partialNamespace = 'twill::partials';
335
336 3
            $viewModule = "'admin.'.$moduleName.'.{$viewName}'";
337 3
            $viewApplication = "'admin.partials.{$viewName}'";
338 3
            $viewModuleTwill = "'twill::'.$moduleName.'.{$viewName}'";
339 3
            $view = $partialNamespace . "." . $viewName;
340
341 3
            if (!isset($moduleName) || is_null($moduleName)) {
342
                $viewModule = $viewApplication;
343
            }
344
345 3
            $expression = explode(',', $expression);
346 3
            $expression = array_slice($expression, 2);
347 3
            $expression = "(" . implode(',', $expression) . ")";
348 3
            if ($expression === "()") {
349 2
                $expression = '([])';
350
            }
351
352
            return "<?php
353 3
            if( view()->exists($viewModule)) {
354 3
                echo \$__env->make($viewModule, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
355 3
            } elseif( view()->exists($viewApplication)) {
356 3
                echo \$__env->make($viewApplication, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
357 3
            } elseif( view()->exists($viewModuleTwill)) {
358 3
                echo \$__env->make($viewModuleTwill, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
359 3
            } elseif( view()->exists('$view')) {
360 3
                echo \$__env->make('$view', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->with{$expression}->render();
361
            }
362
            ?>";
363 70
        });
364
365
        $blade->directive('pushonce', function ($expression) {
366 1
            list($pushName, $pushSub) = explode(':', trim(substr($expression, 1, -1)));
367 1
            $key = '__pushonce_' . $pushName . '_' . str_replace('-', '_', $pushSub);
368 1
            return "<?php if(! isset(\$__env->{$key})): \$__env->{$key} = 1; \$__env->startPush('{$pushName}'); ?>";
369 70
        });
370
371
        $blade->directive('endpushonce', function () {
372 1
            return '<?php $__env->stopPush(); endif; ?>';
373 70
        });
374
375 70
        $blade->component('twill::partials.form.utils._fieldset', 'formFieldset');
376 70
        $blade->component('twill::partials.form.utils._columns', 'formColumns');
377 70
        $blade->component('twill::partials.form.utils._collapsed_fields', 'formCollapsedFields');
378 70
        $blade->component('twill::partials.form.utils._connected_fields', 'formConnectedFields');
379 70
        $blade->component('twill::partials.form.utils._inline_checkboxes', 'formInlineCheckboxes');
380 70
    }
381
382
    /**
383
     * Registers the package additional View Composers.
384
     *
385
     * @return void
386
     */
387 70
    private function addViewComposers()
388
    {
389 70
        if (config('twill.enabled.users-management')) {
390 70
            View::composer(['admin.*', 'twill::*'], CurrentUser::class);
391
        }
392
393 70
        if (config('twill.enabled.media-library')) {
394 70
            View::composer('twill::layouts.main', MediasUploaderConfig::class);
395
        }
396
397 70
        if (config('twill.enabled.file-library')) {
398 70
            View::composer('twill::layouts.main', FilesUploaderConfig::class);
399
        }
400
401 70
        View::composer('twill::partials.navigation.*', ActiveNavigation::class);
402
403
        View::composer(['admin.*', 'templates.*', 'twill::*'], function ($view) {
404 50
            $with = array_merge([
405 50
                'renderForBlocks' => false,
406
                'renderForModal' => false,
407 50
            ], $view->getData());
408
409 50
            return $view->with($with);
410 70
        });
411
412 70
        View::composer(['admin.*', 'twill::*'], Localization::class);
413 70
    }
414
415
    /**
416
     * Registers and publishes the package additional translations.
417
     *
418
     * @return void
419
     */
420 70
    private function registerAndPublishTranslations()
421
    {
422 70
        $translationPath = __DIR__ . '/../lang';
423
424 70
        $this->loadTranslationsFrom($translationPath, 'twill');
425 70
        $this->publishes([$translationPath => resource_path('lang/vendor/twill')], 'translations');
426 70
    }
427
428
    /**
429
     * Get the version number of Twill.
430
     *
431
     * @return string
432
     */
433 70
    public function version()
434
    {
435 70
        return static::VERSION;
436
    }
437
}
438