Completed
Push — develop ( 2e9746...a14a57 )
by Abdelrahman
01:46
created

FoundationServiceProvider::overrideLangJS()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
cc 3
eloc 13
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Foundation\Providers;
6
7
use Illuminate\Routing\Router;
8
use Rinvex\Menus\Facades\Menu;
9
use Spatie\MediaLibrary\Models\Media;
10
use Illuminate\Support\ServiceProvider;
11
use Rinvex\Menus\Factories\MenuFactory;
12
use Illuminate\View\Compilers\BladeCompiler;
13
use Cortex\Foundation\Generators\LangJsGenerator;
14
use Cortex\Foundation\Console\Commands\InstallCommand;
15
use Cortex\Foundation\Console\Commands\MigrateCommand;
16
use Cortex\Foundation\Console\Commands\PublishCommand;
17
use Cortex\Foundation\Console\Commands\CoreSeedCommand;
18
use Cortex\Foundation\Console\Commands\RollbackCommand;
19
use Mariuzzo\LaravelJsLocalization\Commands\LangJsCommand;
20
use Cortex\Foundation\Console\Commands\CoreInstallCommand;
21
use Cortex\Foundation\Console\Commands\CoreMigrateCommand;
22
use Cortex\Foundation\Console\Commands\CorePublishCommand;
23
use Cortex\Foundation\Console\Commands\CoreRollbackCommand;
24
use Cortex\Foundation\Http\Middleware\NotificationMiddleware;
25
use Cortex\Foundation\Overrides\Illuminate\Routing\Redirector;
26
use Cortex\Foundation\Overrides\Illuminate\Routing\UrlGenerator;
27
use Cortex\Foundation\Overrides\Mcamara\LaravelLocalization\LaravelLocalization;
28
29
class FoundationServiceProvider extends ServiceProvider
30
{
31
    /**
32
     * The commands to be registered.
33
     *
34
     * @var array
35
     */
36
    protected $commands = [
37
        InstallCommand::class => 'command.cortex.foundation.install',
38
        MigrateCommand::class => 'command.cortex.foundation.migrate',
39
        PublishCommand::class => 'command.cortex.foundation.publish',
40
        RollbackCommand::class => 'command.cortex.foundation.rollback',
41
        CoreSeedCommand::class => 'command.cortex.foundation.coreseed',
42
        CoreInstallCommand::class => 'command.cortex.foundation.coreinstall',
43
        CoreMigrateCommand::class => 'command.cortex.foundation.coremigrate',
44
        CorePublishCommand::class => 'command.cortex.foundation.corempublish',
45
        CoreRollbackCommand::class => 'command.cortex.foundation.corerollback',
46
    ];
47
48
    /**
49
     * Register any application services.
50
     *
51
     * This service provider is a great spot to register your various container
52
     * bindings with the application. As you can see, we are registering our
53
     * "Registrar" implementation here. You can add your own bindings too!
54
     *
55
     * @return void
56
     */
57
    public function register()
58
    {
59
        $this->overrideNotificationMiddleware();
60
        $this->overrideLaravelLocalization();
61
        $this->overrideUrlGenerator();
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)
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
        // Register menus
111
        $this->registerMenus();
112
    }
113
114
    /**
115
     * Override notification middleware.
116
     *
117
     * @return void
118
     */
119
    protected function overrideNotificationMiddleware()
120
    {
121
        $this->app->singleton('Cortex\Foundation\Http\Middleware\NotificationMiddleware', function ($app) {
122
            return new NotificationMiddleware(
123
                $app['session.store'],
124
                $app['notification'],
125
                $app['config']->get('notification.session_key')
126
            );
127
        });
128
    }
129
130
    /**
131
     * Bind blade compiler.
132
     *
133
     * @return void
134
     */
135
    protected function bindBladeCompiler()
136
    {
137
        $this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
138
139
            // @alerts('container')
140
            $bladeCompiler->directive('alerts', function ($container = null) {
141
                if (strcasecmp('()', $container) === 0) {
142
                    $container = null;
143
                }
144
145
                return "<?php echo app('notification')->container({$container})->show(); ?>";
146
            });
147
        });
148
    }
149
150
    /**
151
     * Override the Redirector instance.
152
     *
153
     * @return void
154
     */
155
    protected function overrideRedirector()
156
    {
157
        $this->app->singleton('redirect', function ($app) {
158
            $redirector = new Redirector($app['url']);
159
160
            // If the session is set on the application instance, we'll inject it into
161
            // the redirector instance. This allows the redirect responses to allow
162
            // for the quite convenient "with" methods that flash to the session.
163
            if (isset($app['session.store'])) {
164
                $redirector->setSession($app['session.store']);
165
            }
166
167
            return $redirector;
168
        });
169
    }
170
171
    /**
172
     * Override the UrlGenerator instance.
173
     *
174
     * @return void
175
     */
176
    protected function overrideUrlGenerator()
177
    {
178
        $this->app->singleton('url', function ($app) {
179
            $routes = $app['router']->getRoutes();
180
181
            // The URL generator needs the route collection that exists on the router.
182
            // Keep in mind this is an object, so we're passing by references here
183
            // and all the registered routes will be available to the generator.
184
            $app->instance('routes', $routes);
185
186
            $url = new UrlGenerator(
187
                $routes, $app->rebinding(
188
                    'request', $this->requestRebinder()
189
                )
190
            );
191
192
            $url->setSessionResolver(function () {
193
                return $this->app['session'];
194
            });
195
196
            // If the route collection is "rebound", for example, when the routes stay
197
            // cached for the application, we will need to rebind the routes on the
198
            // URL generator instance so it has the latest version of the routes.
199
            $app->rebinding('routes', function ($app, $routes) {
200
                $app['url']->setRoutes($routes);
201
            });
202
203
            return $url;
204
        });
205
    }
206
207
    /**
208
     * Get the URL generator request rebinder.
209
     *
210
     * @return \Closure
211
     */
212
    protected function requestRebinder()
213
    {
214
        return function ($app, $request) {
215
            $app['url']->setRequest($request);
216
        };
217
    }
218
219
    /**
220
     * Override the LaravelLocalization instance.
221
     *
222
     * @return void
223
     */
224
    protected function overrideLaravelLocalization()
225
    {
226
        $this->app->singleton('laravellocalization', function () {
227
            return new LaravelLocalization();
228
        });
229
    }
230
231
    /**
232
     * Publish resources.
233
     *
234
     * @return void
235
     */
236
    protected function publishResources()
237
    {
238
        $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...
239
        $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...
240
        $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...
241
        $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...
242
    }
243
244
    /**
245
     * Register menus.
246
     *
247
     * @return void
248
     */
249
    protected function registerMenus()
250
    {
251
        Menu::make('frontarea.header', function (MenuFactory $menu) {
0 ignored issues
show
Unused Code introduced by
The parameter $menu 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...
252
        });
253
        Menu::make('adminarea.header', function (MenuFactory $menu) {
0 ignored issues
show
Unused Code introduced by
The parameter $menu 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...
254
        });
255
        Menu::make('adminarea.sidebar', function (MenuFactory $menu) {
0 ignored issues
show
Unused Code introduced by
The parameter $menu 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...
256
        });
257
    }
258
259
    /**
260
     * Register console commands.
261
     *
262
     * @return void
263
     */
264
    protected function registerCommands()
265
    {
266
        // Register artisan commands
267
        foreach ($this->commands as $key => $value) {
268
            $this->app->singleton($value, function ($app) use ($key) {
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...
269
                return new $key();
270
            });
271
        }
272
273
        $this->commands(array_values($this->commands));
274
    }
275
276
    /**
277
     * Register console commands.
278
     *
279
     * @return void
280
     */
281
    protected function overrideLangJS()
282
    {
283
        // Bind the Laravel JS Localization command into the app IOC.
284
        $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...
285
            $app = $this->app;
286
            $laravelMajorVersion = (int) $app::VERSION;
287
288
            $files = $app['files'];
289
290
            if ($laravelMajorVersion === 4) {
291
                $langs = $app['path.base'].'/app/lang';
292
            } elseif ($laravelMajorVersion === 5) {
293
                $langs = $app['path.base'].'/resources/lang';
294
            }
295
            $messages = $app['config']->get('localization-js.messages');
296
            $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...
297
298
            return new LangJsCommand($generator);
299
        });
300
301
        // Bind the Laravel JS Localization command into Laravel Artisan.
302
        $this->commands('localization.js');
303
    }
304
}
305