Completed
Pull Request — 2.0 (#93)
by
unknown
06:16
created

CoreServiceProvider::getArguments()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Modules\Core\Providers;
4
5
use Illuminate\Routing\Router;
6
use Illuminate\Support\Facades\DB;
7
use Illuminate\Support\ServiceProvider;
8
use Modules\Core\Console\InstallCommand;
9
use Modules\Core\Console\PublishModuleAssetsCommand;
10
use Modules\Core\Console\PublishThemeAssetsCommand;
11
use Modules\Core\Foundation\Theme\ThemeManager;
12
use Modules\Core\Traits\CanPublishConfiguration;
13
use Nwidart\Modules\Module;
14
15
class CoreServiceProvider extends ServiceProvider
16
{
17
    use CanPublishConfiguration;
18
    /**
19
     * Indicates if loading of the provider is deferred.
20
     *
21
     * @var bool
22
     */
23
    protected $defer = false;
24
25
    /**
26
     * @var string
27
     */
28
    protected $prefix = 'asgard';
29
30
    /**
31
     * The filters base class name.
32
     *
33
     * @var array
34
     */
35
    protected $middleware = [
36
        'Core' => [
37
            'permissions'           => 'PermissionMiddleware',
38
            'auth.admin'            => 'AdminMiddleware',
39
            'public.checkLocale'    => 'PublicMiddleware',
40
            'localizationRedirect'  => 'LocalizationMiddleware',
41
            'can' => 'Authorization',
42
        ],
43
    ];
44
45
    public function boot()
46
    {
47
        $this->registerMiddleware($this->app['router']);
48
        $this->registerModuleResourceNamespaces();
49
50
        $this->publishConfig('core', 'available-locales');
51
        $this->publishConfig('core', 'config');
52
        $this->publishConfig('core', 'core');
53
        $this->publishConfig('core', 'settings');
54
55
        $this->bladeDirectives();
56
    }
57
58
    /**
59
     * Register the service provider.
60
     *
61
     * @return void
62
     */
63
    public function register()
64
    {
65
        $this->app->singleton('asgard.isInstalled', function () {
66
            return true === env('INSTALLED', false);
67
        });
68
69
        $this->registerCommands();
70
        $this->registerServices();
71
        $this->setLocalesConfigurations();
72
    }
73
74
    /**
75
     * Get the services provided by the provider.
76
     *
77
     * @return array
78
     */
79
    public function provides()
80
    {
81
        return array();
82
    }
83
84
    /**
85
     * Register the filters.
86
     *
87
     * @param  Router $router
88
     * @return void
89
     */
90
    public function registerMiddleware(Router $router)
91
    {
92
        foreach ($this->middleware as $module => $middlewares) {
93
            foreach ($middlewares as $name => $middleware) {
94
                $class = "Modules\\{$module}\\Http\\Middleware\\{$middleware}";
95
96
                $router->middleware($name, $class);
97
            }
98
        }
99
    }
100
101
    /**
102
     * Register the console commands
103
     */
104
    private function registerCommands()
105
    {
106
        $this->commands([
107
            InstallCommand::class,
108
            PublishThemeAssetsCommand::class,
109
            PublishModuleAssetsCommand::class,
110
        ]);
111
    }
112
113
    private function registerServices()
114
    {
115
        $this->app->singleton(ThemeManager::class, function ($app) {
116
            $path = $app['config']->get('asgard.core.core.themes_path');
117
118
            return new ThemeManager($app, $path);
119
        });
120
    }
121
122
    /**
123
     * Register the modules aliases
124
     */
125
    private function registerModuleResourceNamespaces()
126
    {
127
        foreach ($this->app['modules']->getOrdered() as $module) {
128
            $this->registerViewNamespace($module);
129
            $this->registerLanguageNamespace($module);
130
        }
131
    }
132
133
    /**
134
     * Register the view namespaces for the modules
135
     * @param Module $module
136
     */
137
    protected function registerViewNamespace(Module $module)
138
    {
139
        if ($module->getLowerName() == 'user') {
140
            return;
141
        }
142
        $this->app['view']->addNamespace(
143
            $module->getLowerName(),
144
            $module->getPath() . '/Resources/views'
145
        );
146
    }
147
148
    /**
149
     * Register the language namespaces for the modules
150
     * @param Module $module
151
     */
152
    protected function registerLanguageNamespace(Module $module)
153
    {
154
        $moduleName = $module->getLowerName();
155
156
        $langPath = base_path("resources/lang/$moduleName");
157
        $secondPath = base_path("resources/lang/translation/$moduleName");
158
159
        if ($moduleName !== 'translation' && $this->hasPublishedTranslations($langPath)) {
160
            return $this->loadTranslationsFrom($langPath, $moduleName);
161
        }
162
        if ($this->hasPublishedTranslations($secondPath)) {
163
            return $this->loadTranslationsFrom($secondPath, $moduleName);
164
        }
165
        if ($this->moduleHasCentralisedTranslations($module)) {
166
            return $this->loadTranslationsFrom($this->getCentralisedTranslationPath($module), $moduleName);
167
        }
168
169
        return $this->loadTranslationsFrom($module->getPath() . '/Resources/lang', $moduleName);
170
    }
171
172
    /**
173
     * @param $file
174
     * @param $package
175
     * @return string
176
     */
177
    private function getConfigFilename($file)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
178
    {
179
        return preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($file));
180
    }
181
182
    /**
183
     * Set the locale configuration for
184
     * - laravel localization
185
     * - laravel translatable
186
     */
187
    private function setLocalesConfigurations()
188
    {
189
        if (! $this->app['asgard.isInstalled']) {
190
            return;
191
        }
192
193
        $localeConfig = $this->app['cache']
194
            ->tags('setting.settings', 'global')
195
            ->remember("asgard.locales", 120,
196
                function () {
197
                    return DB::table('setting__settings')->whereName('core::locales')->first();
198
                }
199
            );
200
        if ($localeConfig) {
201
            $locales = json_decode($localeConfig->plainValue);
202
            $availableLocales = [];
203
            foreach ($locales as $locale) {
204
                $availableLocales = array_merge($availableLocales, [$locale => config("available-locales.$locale")]);
205
            }
206
207
            $laravelDefaultLocale = $this->app->config->get('app.locale');
0 ignored issues
show
Bug introduced by
Accessing config on the interface Illuminate\Contracts\Foundation\Application suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
208
209
            if (! in_array($laravelDefaultLocale, array_keys($availableLocales))) {
210
                $this->app->config->set('app.locale', array_keys($availableLocales)[0]);
0 ignored issues
show
Bug introduced by
Accessing config on the interface Illuminate\Contracts\Foundation\Application suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
211
            }
212
            $this->app->config->set('laravellocalization.supportedLocales', $availableLocales);
0 ignored issues
show
Bug introduced by
Accessing config on the interface Illuminate\Contracts\Foundation\Application suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
213
            $this->app->config->set('translatable.locales', $locales);
0 ignored issues
show
Bug introduced by
Accessing config on the interface Illuminate\Contracts\Foundation\Application suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
214
        }
215
    }
216
217
    /**
218
     * @param string $path
219
     * @return bool
220
     */
221
    private function hasPublishedTranslations($path)
222
    {
223
        return is_dir($path);
224
    }
225
226
    /**
227
     * Does a Module have it's Translations centralised in the Translation module?
228
     * @param Module $module
229
     * @return bool
230
     */
231
    private function moduleHasCentralisedTranslations(Module $module)
232
    {
233
        if (! array_has($this->app['modules']->enabled(), 'Translation')) {
234
            return false;
235
        }
236
237
        return is_dir($this->getCentralisedTranslationPath($module));
238
    }
239
240
    /**
241
     * Get the absolute path to the Centralised Translations for a Module (via the Translations module)
242
     * @param Module $module
243
     * @return string
244
     */
245
    private function getCentralisedTranslationPath(Module $module)
246
    {
247
        return $this->app['modules']->find('Translation')->getPath() . "/Resources/lang/{$module->getLowerName()}";
248
    }
249
250
    /**
251
     * List of Custom Blade Directives
252
     */
253
    public function bladeDirectives()
254
    {
255
        /**
256
         * Set variable.
257
         * Usage: @set($variable, value)
258
         */
259
        Blade::directive('set', function ($expression) {
260
            list($variable, $value) = $this->getArguments($expression);
261
262
            return "<?php {$variable} = {$value}; ?>";
263
        });
264
265
        /**
266
         * Php explode()
267
         * Usage: @explode($delimiter, $string)
268
         */
269
        Blade::directive('explode', function ($expression) {
270
            list($delimiter, $string) = $this->getArguments($expression);
271
272
            return "<?php echo explode({$delimiter}, {$string}); ?>";
273
        });
274
275
        /**
276
         * php implode()
277
         * Usage: @implode($delimiter, $array)
278
         */
279
        Blade::directive('implode', function ($expression) {
280
            list($delimiter, $array) = $this->getArguments($expression);
281
282
            return "<?php echo implode({$delimiter}, {$array}); ?>";
283
        });
284
    }
285
286
    /**
287
     * Get argument array from argument string.
288
     * @param $argumentString
289
     * @return array
290
     */
291
    private function getArguments($argumentString)
292
    {
293
        return explode(', ', str_replace(['(', ')'], '', $argumentString));
294
    }
295
}
296