Passed
Pull Request — 2.x (#597)
by Antonio Carlos
07:12
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 72
    public function boot()
67
    {
68 72
        $this->requireHelpers();
69
70 72
        $this->publishConfigs();
71 72
        $this->publishMigrations();
72 72
        $this->publishAssets();
73
74 72
        $this->registerCommands();
75
76 72
        $this->registerAndPublishViews();
77 72
        $this->registerAndPublishTranslations();
78
79 72
        $this->extendBlade();
80 72
        $this->addViewComposers();
81 72
    }
82
83
    /**
84
     * @return void
85
     */
86 72
    private function requireHelpers()
87
    {
88 72
        require_once __DIR__ . '/Helpers/routes_helpers.php';
89 72
        require_once __DIR__ . '/Helpers/i18n_helpers.php';
90 72
        require_once __DIR__ . '/Helpers/media_library_helpers.php';
91 72
        require_once __DIR__ . '/Helpers/frontend_helpers.php';
92 72
        require_once __DIR__ . '/Helpers/migrations_helpers.php';
93 72
        require_once __DIR__ . '/Helpers/helpers.php';
94 72
    }
95
96
    /**
97
     * Registers the package services.
98
     *
99
     * @return void
100
     */
101 72
    public function register()
102
    {
103 72
        $this->mergeConfigs();
104
105 72
        $this->registerProviders();
106 72
        $this->registerAliases();
107
108 72
        Relation::morphMap([
109 72
            'users' => User::class,
110
            'media' => Media::class,
111
            'files' => File::class,
112
            'blocks' => Block::class,
113
        ]);
114
115 72
        config(['twill.version' => $this->version()]);
116 72
    }
117
118
    /**
119
     * Registers the package service providers.
120
     *
121
     * @return void
122
     */
123 72
    private function registerProviders()
124
    {
125 72
        foreach ($this->providers as $provider) {
126 72
            $this->app->register($provider);
127
        }
128
129 72
        if (config('twill.enabled.media-library')) {
130
            $this->app->singleton('imageService', function () {
131 9
                return $this->app->make(config('twill.media_library.image_service'));
132 72
            });
133
        }
134
135 72
        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 72
            });
139
        }
140 72
    }
141
142
    /**
143
     * Registers the package facade aliases.
144
     *
145
     * @return void
146
     */
147 72
    private function registerAliases()
148
    {
149 72
        $loader = AliasLoader::getInstance();
150
151 72
        if (config('twill.enabled.media-library')) {
152 72
            $loader->alias('ImageService', ImageService::class);
153
        }
154
155 72
        if (config('twill.enabled.file-library')) {
156 72
            $loader->alias('FileService', FileService::class);
157
        }
158
159 72
    }
160
161
    /**
162
     * Defines the package configuration files for publishing.
163
     *
164
     * @return void
165
     */
166 72
    private function publishConfigs()
167
    {
168 72
        if (config('twill.enabled.users-management')) {
169 72
            config(['auth.providers.twill_users' => [
170 72
                'driver' => 'eloquent',
171
                'model' => User::class,
172
            ]]);
173
174 72
            config(['auth.guards.twill_users' => [
175 72
                'driver' => 'session',
176
                'provider' => 'twill_users',
177
            ]]);
178
179 72
            config(['auth.passwords.twill_users' => [
180 72
                'provider' => 'twill_users',
181 72
                'table' => config('twill.password_resets_table', 'twill_password_resets'),
182 72
                'expire' => 60,
183
            ]]);
184
        }
185
186 72
        config(['activitylog.enabled' => config('twill.enabled.dashboard') ? true : config('twill.enabled.activitylog')]);
187 72
        config(['activitylog.subject_returns_soft_deleted_models' => true]);
188
189 72
        config(['analytics.service_account_credentials_json' => config('twill.dashboard.analytics.service_account_credentials_json', storage_path('app/analytics/service-account-credentials.json'))]);
190
191 72
        $this->publishes([__DIR__ . '/../config/twill-publish.php' => config_path('twill.php')], 'config');
192 72
        $this->publishes([__DIR__ . '/../config/twill-navigation.php' => config_path('twill-navigation.php')], 'config');
193 72
        $this->publishes([__DIR__ . '/../config/translatable.php' => config_path('translatable.php')], 'config');
194 72
    }
195
196
    /**
197
     * Merges the package configuration files into the given configuration namespaces.
198
     *
199
     * @return void
200
     */
201 72
    private function mergeConfigs()
202
    {
203 72
        $this->mergeConfigFrom(__DIR__ . '/../config/twill.php', 'twill');
204 72
        $this->mergeConfigFrom(__DIR__ . '/../config/frontend.php', 'twill.frontend');
205 72
        $this->mergeConfigFrom(__DIR__ . '/../config/debug.php', 'twill.debug');
206 72
        $this->mergeConfigFrom(__DIR__ . '/../config/seo.php', 'twill.seo');
207 72
        $this->mergeConfigFrom(__DIR__ . '/../config/blocks.php', 'twill.block_editor');
208 72
        $this->mergeConfigFrom(__DIR__ . '/../config/enabled.php', 'twill.enabled');
209 72
        $this->mergeConfigFrom(__DIR__ . '/../config/file-library.php', 'twill.file_library');
210 72
        $this->mergeConfigFrom(__DIR__ . '/../config/media-library.php', 'twill.media_library');
211 72
        $this->mergeConfigFrom(__DIR__ . '/../config/imgix.php', 'twill.imgix');
212 72
        $this->mergeConfigFrom(__DIR__ . '/../config/glide.php', 'twill.glide');
213 72
        $this->mergeConfigFrom(__DIR__ . '/../config/dashboard.php', 'twill.dashboard');
214 72
        $this->mergeConfigFrom(__DIR__ . '/../config/oauth.php', 'twill.oauth');
215 72
        $this->mergeConfigFrom(__DIR__ . '/../config/disks.php', 'filesystems.disks');
216 72
        $this->mergeConfigFrom(__DIR__ . '/../config/services.php', 'services');
217 72
    }
218
219 72
    private function publishMigrations()
220
    {
221 72
        if (config('twill.load_default_migrations', true)) {
222 72
            $this->loadMigrationsFrom(__DIR__ . '/../migrations/default');
223
        }
224
225 72
        $this->publishes([
226 72
            __DIR__ . '/../migrations/default' => database_path('migrations'),
227 72
        ], 'migrations');
228
229 72
        $this->publishOptionalMigration('users-2fa');
230 72
        $this->publishOptionalMigration('users-oauth');
231 72
    }
232
233 72
    private function publishOptionalMigration($feature)
234
    {
235 72
        if (config('twill.enabled.' . $feature, false)) {
236 68
            $this->loadMigrationsFrom(__DIR__ . '/../migrations/optional/' . $feature);
237
238 68
            $this->publishes([
239 68
                __DIR__ . '/../migrations/optional/' . $feature => database_path('migrations'),
240 68
            ], 'migrations');
241
        }
242 72
    }
243
244
    /**
245
     * @return void
246
     */
247 72
    private function publishAssets()
248
    {
249 72
        $this->publishes([
250 72
            __DIR__ . '/../dist' => public_path(),
251 72
        ], 'assets');
252 72
    }
253
254
    /**
255
     * @return void
256
     */
257 72
    private function registerAndPublishViews()
258
    {
259 72
        $viewPath = __DIR__ . '/../views';
260
261 72
        $this->loadViewsFrom($viewPath, 'twill');
262 72
        $this->publishes([$viewPath => resource_path('views/vendor/twill')], 'views');
263 72
    }
264
265
    /**
266
     * @return void
267
     */
268 72
    private function registerCommands()
269
    {
270 72
        $this->commands([
271 72
            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 72
    }
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 72
    private function extendBlade()
313
    {
314 72
        $blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
315
316
        $blade->directive('dd', function ($param) {
317
            return "<?php dd({$param}); ?>";
318 72
        });
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 72
        });
324
325
        $blade->directive('formField', function ($expression) {
326 4
            return $this->includeView('partials.form._', $expression);
327 72
        });
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 72
        });
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 72
        });
370
371
        $blade->directive('endpushonce', function () {
372 1
            return '<?php $__env->stopPush(); endif; ?>';
373 72
        });
374
375 72
        $blade->component('twill::partials.form.utils._fieldset', 'formFieldset');
376 72
        $blade->component('twill::partials.form.utils._columns', 'formColumns');
377 72
        $blade->component('twill::partials.form.utils._collapsed_fields', 'formCollapsedFields');
378 72
        $blade->component('twill::partials.form.utils._connected_fields', 'formConnectedFields');
379 72
        $blade->component('twill::partials.form.utils._inline_checkboxes', 'formInlineCheckboxes');
380 72
    }
381
382
    /**
383
     * Registers the package additional View Composers.
384
     *
385
     * @return void
386
     */
387 72
    private function addViewComposers()
388
    {
389 72
        if (config('twill.enabled.users-management')) {
390 72
            View::composer(['admin.*', 'twill::*'], CurrentUser::class);
391
        }
392
393 72
        if (config('twill.enabled.media-library')) {
394 72
            View::composer('twill::layouts.main', MediasUploaderConfig::class);
395
        }
396
397 72
        if (config('twill.enabled.file-library')) {
398 72
            View::composer('twill::layouts.main', FilesUploaderConfig::class);
399
        }
400
401 72
        View::composer('twill::partials.navigation.*', ActiveNavigation::class);
402
403
        View::composer(['admin.*', 'templates.*', 'twill::*'], function ($view) {
404 52
            $with = array_merge([
405 52
                'renderForBlocks' => false,
406
                'renderForModal' => false,
407 52
            ], $view->getData());
408
409 52
            return $view->with($with);
410 72
        });
411
412 72
        View::composer(['admin.*', 'twill::*'], Localization::class);
413 72
    }
414
415
    /**
416
     * Registers and publishes the package additional translations.
417
     *
418
     * @return void
419
     */
420 72
    private function registerAndPublishTranslations()
421
    {
422 72
        $translationPath = __DIR__ . '/../lang';
423
424 72
        $this->loadTranslationsFrom($translationPath, 'twill');
425 72
        $this->publishes([$translationPath => resource_path('lang/vendor/twill')], 'translations');
426 72
    }
427
428
    /**
429
     * Get the version number of Twill.
430
     *
431
     * @return string
432
     */
433 72
    public function version()
434
    {
435 72
        return static::VERSION;
436
    }
437
}
438