Passed
Push — master ( e1e679...09e224 )
by Quentin
10:29
created

TwillServiceProvider::extendBlade()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 68
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 35
CRAP Score 5.1608

Importance

Changes 0
Metric Value
cc 5
eloc 43
nc 1
nop 0
dl 0
loc 68
ccs 35
cts 43
cp 0.8139
crap 5.1608
rs 8.9208
c 0
b 0
f 0

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