Completed
Push — develop ( cbad9d...de1065 )
by Abdelrahman
13:09
created

FoundationServiceProvider   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 286
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 10
dl 0
loc 286
rs 10
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A overrideNotificationMiddleware() 0 10 1
A bindBladeCompiler() 0 14 2
A overrideRedirector() 0 15 2
B overrideUrlGenerator() 0 30 1
A requestRebinder() 0 6 1
A overrideLaravelLocalization() 0 6 1
A publishResources() 0 7 1
A register() 0 19 2
B boot() 0 29 4
A registerCommands() 0 9 2
A overrideLangJS() 0 23 3
A bindBlueprintMacro() 0 23 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Foundation\Providers;
6
7
use Illuminate\Routing\Router;
8
use Spatie\MediaLibrary\Models\Media;
9
use Illuminate\Support\ServiceProvider;
10
use Illuminate\Database\Schema\Blueprint;
11
use Illuminate\View\Compilers\BladeCompiler;
12
use Cortex\Foundation\Generators\LangJsGenerator;
13
use Cortex\Foundation\Console\Commands\InstallCommand;
14
use Cortex\Foundation\Console\Commands\MigrateCommand;
15
use Cortex\Foundation\Console\Commands\PublishCommand;
16
use Cortex\Foundation\Console\Commands\CoreSeedCommand;
17
use Cortex\Foundation\Console\Commands\RollbackCommand;
18
use Cortex\Foundation\Console\Commands\CoreInstallCommand;
19
use Cortex\Foundation\Console\Commands\CoreMigrateCommand;
20
use Cortex\Foundation\Console\Commands\CorePublishCommand;
21
use Mariuzzo\LaravelJsLocalization\Commands\LangJsCommand;
22
use Cortex\Foundation\Console\Commands\CoreRollbackCommand;
23
use Cortex\Foundation\Http\Middleware\NotificationMiddleware;
24
use Cortex\Foundation\Overrides\Illuminate\Routing\Redirector;
25
use Cortex\Foundation\Overrides\Illuminate\Routing\UrlGenerator;
26
use Cortex\Foundation\Overrides\Mcamara\LaravelLocalization\LaravelLocalization;
27
28
class FoundationServiceProvider extends ServiceProvider
29
{
30
    /**
31
     * The commands to be registered.
32
     *
33
     * @var array
34
     */
35
    protected $commands = [
36
        InstallCommand::class => 'command.cortex.foundation.install',
37
        MigrateCommand::class => 'command.cortex.foundation.migrate',
38
        PublishCommand::class => 'command.cortex.foundation.publish',
39
        RollbackCommand::class => 'command.cortex.foundation.rollback',
40
        CoreSeedCommand::class => 'command.cortex.foundation.coreseed',
41
        CoreInstallCommand::class => 'command.cortex.foundation.coreinstall',
42
        CoreMigrateCommand::class => 'command.cortex.foundation.coremigrate',
43
        CorePublishCommand::class => 'command.cortex.foundation.corempublish',
44
        CoreRollbackCommand::class => 'command.cortex.foundation.corerollback',
45
    ];
46
47
    /**
48
     * Register any application services.
49
     *
50
     * This service provider is a great spot to register your various container
51
     * bindings with the application. As you can see, we are registering our
52
     * "Registrar" implementation here. You can add your own bindings too!
53
     *
54
     * @return void
55
     */
56
    public function register(): void
57
    {
58
        $this->overrideNotificationMiddleware();
59
        $this->overrideLaravelLocalization();
60
        $this->overrideUrlGenerator();
61
        $this->bindBlueprintMacro();
62
        $this->overrideRedirector();
63
        $this->bindBladeCompiler();
64
        $this->overrideLangJS();
65
66
        // Merge config
67
        $this->mergeConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'cortex.foundation');
68
69
        // Override datatables html builder
70
        $this->app->bind(\Yajra\DataTables\Html\Builder::class, \Cortex\Foundation\Overrides\Yajra\DataTables\Html\Builder::class);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 131 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
71
72
        // Register console commands
73
        ! $this->app->runningInConsole() || $this->registerCommands();
74
    }
75
76
    /**
77
     * Bootstrap any application services.
78
     *
79
     * @return void
80
     */
81
    public function boot(Router $router): void
82
    {
83
        // Early set application locale globaly
84
        $router->pattern('locale', '[a-z]{2}');
85
        $this->app['laravellocalization']->setLocale();
86
87
        $router->model('media', Media::class);
88
89
        // Load resources
90
        $this->loadRoutesFrom(__DIR__.'/../../routes/web.php');
91
        $this->loadViewsFrom(__DIR__.'/../../resources/views', 'cortex/foundation');
92
        $this->loadTranslationsFrom(__DIR__.'/../../resources/lang', 'cortex/foundation');
93
        ! $this->app->runningInConsole() || $this->loadMigrationsFrom(__DIR__.'/../../database/migrations');
94
        $this->app->afterResolving('blade.compiler', function () {
95
            require __DIR__.'/../../routes/menus.php';
96
        });
97
98
        // Publish Resources
99
        ! $this->app->runningInConsole() || $this->publishResources();
100
101
        $this->app->booted(function () {
102
            if ($this->app->routesAreCached()) {
103
                require $this->app->getCachedRoutesPath();
104
            } else {
105
                $this->app['router']->getRoutes()->refreshNameLookups();
106
                $this->app['router']->getRoutes()->refreshActionLookups();
107
            }
108
        });
109
    }
110
111
    /**
112
     * Override notification middleware.
113
     *
114
     * @return void
115
     */
116
    protected function overrideNotificationMiddleware(): void
117
    {
118
        $this->app->singleton('Cortex\Foundation\Http\Middleware\NotificationMiddleware', function ($app) {
119
            return new NotificationMiddleware(
120
                $app['session.store'],
121
                $app['notification'],
122
                $app['config']->get('notification.session_key')
123
            );
124
        });
125
    }
126
127
    /**
128
     * Bind blade compiler.
129
     *
130
     * @return void
131
     */
132
    protected function bindBladeCompiler(): void
133
    {
134
        $this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
135
136
            // @alerts('container')
137
            $bladeCompiler->directive('alerts', function ($container = null) {
138
                if (strcasecmp('()', $container) === 0) {
139
                    $container = null;
140
                }
141
142
                return "<?php echo app('notification')->container({$container})->show(); ?>";
143
            });
144
        });
145
    }
146
147
    /**
148
     * Override the Redirector instance.
149
     *
150
     * @return void
151
     */
152
    protected function overrideRedirector(): void
153
    {
154
        $this->app->singleton('redirect', function ($app) {
155
            $redirector = new Redirector($app['url']);
156
157
            // If the session is set on the application instance, we'll inject it into
158
            // the redirector instance. This allows the redirect responses to allow
159
            // for the quite convenient "with" methods that flash to the session.
160
            if (isset($app['session.store'])) {
161
                $redirector->setSession($app['session.store']);
162
            }
163
164
            return $redirector;
165
        });
166
    }
167
168
    /**
169
     * Override the UrlGenerator instance.
170
     *
171
     * @return void
172
     */
173
    protected function overrideUrlGenerator(): void
174
    {
175
        $this->app->singleton('url', function ($app) {
176
            $routes = $app['router']->getRoutes();
177
178
            // The URL generator needs the route collection that exists on the router.
179
            // Keep in mind this is an object, so we're passing by references here
180
            // and all the registered routes will be available to the generator.
181
            $app->instance('routes', $routes);
182
183
            $url = new UrlGenerator(
184
                $routes, $app->rebinding(
185
                    'request', $this->requestRebinder()
186
                )
187
            );
188
189
            $url->setSessionResolver(function () {
190
                return $this->app['session'];
191
            });
192
193
            // If the route collection is "rebound", for example, when the routes stay
194
            // cached for the application, we will need to rebind the routes on the
195
            // URL generator instance so it has the latest version of the routes.
196
            $app->rebinding('routes', function ($app, $routes) {
197
                $app['url']->setRoutes($routes);
198
            });
199
200
            return $url;
201
        });
202
    }
203
204
    /**
205
     * Get the URL generator request rebinder.
206
     *
207
     * @return \Closure
208
     */
209
    protected function requestRebinder()
210
    {
211
        return function ($app, $request) {
212
            $app['url']->setRequest($request);
213
        };
214
    }
215
216
    /**
217
     * Override the LaravelLocalization instance.
218
     *
219
     * @return void
220
     */
221
    protected function overrideLaravelLocalization(): void
222
    {
223
        $this->app->singleton('laravellocalization', function () {
224
            return new LaravelLocalization();
225
        });
226
    }
227
228
    /**
229
     * Publish resources.
230
     *
231
     * @return void
232
     */
233
    protected function publishResources(): void
234
    {
235
        $this->publishes([realpath(__DIR__.'/../../database/migrations') => database_path('migrations')], 'cortex-foundation-migrations');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 138 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
236
        $this->publishes([realpath(__DIR__.'/../../config/config.php') => config_path('cortex.foundation.php')], 'cortex-foundation-config');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 141 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
237
        $this->publishes([realpath(__DIR__.'/../../resources/lang') => resource_path('lang/vendor/cortex/foundation')], 'cortex-foundation-lang');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 146 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
238
        $this->publishes([realpath(__DIR__.'/../../resources/views') => resource_path('views/vendor/cortex/foundation')], 'cortex-foundation-views');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 149 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
239
    }
240
241
    /**
242
     * Register console commands.
243
     *
244
     * @return void
245
     */
246
    protected function registerCommands(): void
247
    {
248
        // Register artisan commands
249
        foreach ($this->commands as $key => $value) {
250
            $this->app->singleton($value, $key);
251
        }
252
253
        $this->commands(array_values($this->commands));
254
    }
255
256
    /**
257
     * Register console commands.
258
     *
259
     * @return void
260
     */
261
    protected function overrideLangJS(): void
262
    {
263
        // Bind the Laravel JS Localization command into the app IOC.
264
        $this->app->singleton('localization.js', function ($app) {
0 ignored issues
show
Unused Code introduced by
The parameter $app is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
265
            $app = $this->app;
266
            $laravelMajorVersion = (int) $app::VERSION;
267
268
            $files = $app['files'];
269
270
            if ($laravelMajorVersion === 4) {
271
                $langs = $app['path.base'].'/app/lang';
272
            } elseif ($laravelMajorVersion === 5) {
273
                $langs = $app['path.base'].'/resources/lang';
274
            }
275
            $messages = $app['config']->get('localization-js.messages');
276
            $generator = new LangJsGenerator($files, $langs, $messages);
0 ignored issues
show
Bug introduced by
The variable $langs does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
277
278
            return new LangJsCommand($generator);
279
        });
280
281
        // Bind the Laravel JS Localization command into Laravel Artisan.
282
        $this->commands('localization.js');
283
    }
284
285
    /**
286
     * Bind blueprint macro.
287
     *
288
     * @return void
289
     */
290
    protected function bindBlueprintMacro(): void
291
    {
292
        // Get users model
293
        $userModel = config('auth.providers.'.config('auth.guards.'.config('auth.defaults.guard').'.provider').'.model');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
294
295
        Blueprint::macro('auditable', function() use ($userModel) {
296
            // Columns
297
            $this->unsignedInteger('created_by')->after('created_at')->nullable();
0 ignored issues
show
Bug introduced by
The method unsignedInteger() does not seem to exist on object<Cortex\Foundation...ndationServiceProvider>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
298
            $this->unsignedInteger('updated_by')->after('updated_at')->nullable();
0 ignored issues
show
Bug introduced by
The method unsignedInteger() does not seem to exist on object<Cortex\Foundation...ndationServiceProvider>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
299
300
            // Indexes
301
            $this->foreign('created_by')->references('id')->on((new $userModel())->getTable())
0 ignored issues
show
Bug introduced by
The method foreign() does not seem to exist on object<Cortex\Foundation...ndationServiceProvider>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
302
                 ->onDelete('cascade')->onUpdate('cascade');
303
            $this->foreign('updated_by')->references('id')->on((new $userModel())->getTable())
0 ignored issues
show
Bug introduced by
The method foreign() does not seem to exist on object<Cortex\Foundation...ndationServiceProvider>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
304
                 ->onDelete('cascade')->onUpdate('cascade');
305
        });
306
307
        Blueprint::macro('dropAuditable', function() {
308
            $this->dropForeign($this->createIndexName('foreign', ['created_by']));
0 ignored issues
show
Bug introduced by
The method createIndexName() does not seem to exist on object<Cortex\Foundation...ndationServiceProvider>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method dropForeign() does not seem to exist on object<Cortex\Foundation...ndationServiceProvider>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
309
            $this->dropForeign($this->createIndexName('foreign', ['updated_by']));
0 ignored issues
show
Bug introduced by
The method createIndexName() does not seem to exist on object<Cortex\Foundation...ndationServiceProvider>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method dropForeign() does not seem to exist on object<Cortex\Foundation...ndationServiceProvider>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
310
            $this->dropColumn(['created_by', 'updated_by']);
0 ignored issues
show
Bug introduced by
The method dropColumn() does not seem to exist on object<Cortex\Foundation...ndationServiceProvider>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
311
        });
312
    }
313
}
314