Passed
Pull Request — 2.x (#586)
by Bekzat
04:25
created

TwillServiceProvider::includeView()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

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