IgnitionServiceProvider   A
last analyzed

Complexity

Total Complexity 42

Size/Duplication

Total Lines 370
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 22

Importance

Changes 0
Metric Value
dl 0
loc 370
rs 9.0399
c 0
b 0
f 0
wmc 42
lcom 1
cbo 22

21 Methods

Rating   Name   Duplication   Size   Complexity  
A registerViewEngines() 0 16 2
A boot() 0 23 2
A register() 0 24 3
A registerSolutionProviderRepository() 0 10 1
A registerExceptionRenderer() 0 8 1
A registerWhoopsHandler() 0 8 1
A registerIgnitionConfig() 0 18 3
A registerFlare() 0 24 1
A registerLogHandler() 0 27 2
A getLogLevel() 0 10 2
A registerLogRecorder() 0 10 1
A registerDumpCollector() 0 10 1
A registerCommands() 0 15 3
A registerHousekeepingRoutes() 0 27 2
A registerQueryRecorder() 0 10 1
A registerBuiltInMiddleware() 0 28 4
A getDefaultSolutions() 0 19 1
A hasCustomViewEnginesRegistered() 0 14 3
A bindLogListener() 0 16 3
A getConfigFileLocation() 0 16 3
A setupQueue() 0 14 2

How to fix   Complexity   

Complex Class

Complex classes like IgnitionServiceProvider often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use IgnitionServiceProvider, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Facade\Ignition;
4
5
use Facade\FlareClient\Flare;
6
use Facade\FlareClient\Http\Client;
7
use Facade\Ignition\Commands\SolutionMakeCommand;
8
use Facade\Ignition\Commands\TestCommand;
9
use Facade\Ignition\Context\LaravelContextDetector;
10
use Facade\Ignition\DumpRecorder\DumpRecorder;
11
use Facade\Ignition\ErrorPage\IgnitionWhoopsHandler;
12
use Facade\Ignition\ErrorPage\Renderer;
13
use Facade\Ignition\Exceptions\InvalidConfig;
14
use Facade\Ignition\Http\Controllers\ExecuteSolutionController;
15
use Facade\Ignition\Http\Controllers\HealthCheckController;
16
use Facade\Ignition\Http\Controllers\ScriptController;
17
use Facade\Ignition\Http\Controllers\ShareReportController;
18
use Facade\Ignition\Http\Controllers\StyleController;
19
use Facade\Ignition\Http\Middleware\IgnitionConfigValueEnabled;
20
use Facade\Ignition\Http\Middleware\IgnitionEnabled;
21
use Facade\Ignition\Logger\FlareHandler;
22
use Facade\Ignition\LogRecorder\LogRecorder;
23
use Facade\Ignition\Middleware\AddDumps;
24
use Facade\Ignition\Middleware\AddEnvironmentInformation;
25
use Facade\Ignition\Middleware\AddGitInformation;
26
use Facade\Ignition\Middleware\AddLogs;
27
use Facade\Ignition\Middleware\AddQueries;
28
use Facade\Ignition\Middleware\AddSolutions;
29
use Facade\Ignition\Middleware\CustomizeGrouping;
30
use Facade\Ignition\Middleware\SetNotifierName;
31
use Facade\Ignition\QueryRecorder\QueryRecorder;
32
use Facade\Ignition\SolutionProviders\BadMethodCallSolutionProvider;
33
use Facade\Ignition\SolutionProviders\DefaultDbNameSolutionProvider;
34
use Facade\Ignition\SolutionProviders\IncorrectValetDbCredentialsSolutionProvider;
35
use Facade\Ignition\SolutionProviders\InvalidRouteActionSolutionProvider;
36
use Facade\Ignition\SolutionProviders\MergeConflictSolutionProvider;
37
use Facade\Ignition\SolutionProviders\MissingAppKeySolutionProvider;
38
use Facade\Ignition\SolutionProviders\MissingColumnSolutionProvider;
39
use Facade\Ignition\SolutionProviders\MissingImportSolutionProvider;
40
use Facade\Ignition\SolutionProviders\MissingPackageSolutionProvider;
41
use Facade\Ignition\SolutionProviders\RunningLaravelDuskInProductionProvider;
42
use Facade\Ignition\SolutionProviders\SolutionProviderRepository;
43
use Facade\Ignition\SolutionProviders\TableNotFoundSolutionProvider;
44
use Facade\Ignition\SolutionProviders\UndefinedVariableSolutionProvider;
45
use Facade\Ignition\SolutionProviders\UnknownValidationSolutionProvider;
46
use Facade\Ignition\SolutionProviders\ViewNotFoundSolutionProvider;
47
use Facade\Ignition\Views\Engines\CompilerEngine;
48
use Facade\Ignition\Views\Engines\PhpEngine;
49
use Facade\IgnitionContracts\SolutionProviderRepository as SolutionProviderRepositoryContract;
50
use Illuminate\Foundation\Application;
51
use Illuminate\Log\Events\MessageLogged;
52
use Illuminate\Log\LogManager;
53
use Illuminate\Queue\QueueManager;
54
use Illuminate\Support\Arr;
55
use Illuminate\Support\Facades\Log;
56
use Illuminate\Support\Facades\Route;
57
use Illuminate\Support\ServiceProvider;
58
use Illuminate\View\Engines\CompilerEngine as LaravelCompilerEngine;
59
use Illuminate\View\Engines\PhpEngine as LaravelPhpEngine;
60
use Monolog\Logger;
61
use Throwable;
62
use Whoops\Handler\HandlerInterface;
63
64
class IgnitionServiceProvider extends ServiceProvider
65
{
66
    public function boot()
67
    {
68
        if ($this->app->runningInConsole()) {
69
            $this->publishes([
70
                __DIR__.'/../config/flare.php' => config_path('flare.php'),
71
            ], 'flare-config');
72
73
            $this->publishes([
74
                __DIR__.'/../config/ignition.php' => config_path('ignition.php'),
75
            ], 'ignition-config');
76
        }
77
78
        $this
79
            ->registerViewEngines()
80
            ->registerHousekeepingRoutes()
81
            ->registerLogHandler()
82
            ->registerCommands()
83
            ->setupQueue($this->app->queue);
0 ignored issues
show
Bug introduced by
Accessing queue 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...
84
85
        $this->app->make(QueryRecorder::class)->register();
86
        $this->app->make(LogRecorder::class)->register();
87
        $this->app->make(DumpRecorder::class)->register();
88
    }
89
90
    public function register()
91
    {
92
        $this->mergeConfigFrom(__DIR__.'/../config/flare.php', 'flare');
93
        $this->mergeConfigFrom(__DIR__.'/../config/ignition.php', 'ignition');
94
95
        $this
96
            ->registerSolutionProviderRepository()
97
            ->registerExceptionRenderer()
98
            ->registerWhoopsHandler()
99
            ->registerIgnitionConfig()
100
            ->registerFlare()
101
            ->registerLogRecorder()
102
            ->registerDumpCollector();
103
104
        if (config('flare.reporting.report_queries')) {
105
            $this->registerQueryRecorder();
106
        }
107
108
        if (config('flare.reporting.anonymize_ips')) {
109
            $this->app->get('flare.client')->anonymizeIp();
110
        }
111
112
        $this->registerBuiltInMiddleware();
113
    }
114
115
    protected function registerViewEngines()
116
    {
117
        if (! $this->hasCustomViewEnginesRegistered()) {
118
            return $this;
119
        }
120
121
        $this->app->make('view.engine.resolver')->register('php', function () {
122
            return new PhpEngine();
123
        });
124
125
        $this->app->make('view.engine.resolver')->register('blade', function () {
126
            return new CompilerEngine($this->app['blade.compiler']);
127
        });
128
129
        return $this;
130
    }
131
132
    protected function registerHousekeepingRoutes()
133
    {
134
        if ($this->app->runningInConsole()) {
135
            return $this;
136
        }
137
138
        Route::group([
139
            'as' => 'ignition.',
140
            'prefix' => config('ignition.housekeeping_endpoint_prefix', '_ignition'),
141
            'middleware' => [IgnitionEnabled::class],
142
        ], function () {
143
            Route::get('health-check', HealthCheckController::class)->name('healthCheck');
144
145
            Route::post('execute-solution', ExecuteSolutionController::class)
146
                ->middleware(IgnitionConfigValueEnabled::class.':enableRunnableSolutions')
147
                ->name('executeSolution');
148
149
            Route::post('share-report', ShareReportController::class)
150
                ->middleware(IgnitionConfigValueEnabled::class.':enableShareButton')
151
                ->name('shareReport');
152
153
            Route::get('scripts/{script}', ScriptController::class)->name('scripts');
154
            Route::get('styles/{style}', StyleController::class)->name('styles');
155
        });
156
157
        return $this;
158
    }
159
160
    protected function registerSolutionProviderRepository()
161
    {
162
        $this->app->singleton(SolutionProviderRepositoryContract::class, function () {
163
            $defaultSolutions = $this->getDefaultSolutions();
164
165
            return new SolutionProviderRepository($defaultSolutions);
166
        });
167
168
        return $this;
169
    }
170
171
    protected function registerExceptionRenderer()
172
    {
173
        $this->app->bind(Renderer::class, function () {
174
            return new Renderer(__DIR__.'/../resources/views/');
175
        });
176
177
        return $this;
178
    }
179
180
    protected function registerWhoopsHandler()
181
    {
182
        $this->app->bind(HandlerInterface::class, function (Application $app) {
183
            return $app->make(IgnitionWhoopsHandler::class);
184
        });
185
186
        return $this;
187
    }
188
189
    protected function registerIgnitionConfig()
190
    {
191
        $this->app->singleton(IgnitionConfig::class, function () {
192
            $options = [];
193
194
            try {
195
                if ($configPath = $this->getConfigFileLocation()) {
196
                    $options = require $configPath;
197
                }
198
            } catch (Throwable $e) {
199
                // possible open_basedir restriction
200
            }
201
202
            return new IgnitionConfig($options);
203
        });
204
205
        return $this;
206
    }
207
208
    protected function registerFlare()
209
    {
210
        $this->app->singleton('flare.http', function () {
211
            return new Client(
212
                config('flare.key'),
213
                config('flare.secret'),
214
                config('flare.base_url', 'https://flareapp.io/api')
215
            );
216
        });
217
218
        $this->app->alias('flare.http', Client::class);
219
220
        $this->app->singleton('flare.client', function () {
221
            $client = new Flare($this->app->get('flare.http'), new LaravelContextDetector, $this->app);
222
            $client->applicationPath(base_path());
223
            $client->stage(config('app.env'));
224
225
            return $client;
226
        });
227
228
        $this->app->alias('flare.client', Flare::class);
229
230
        return $this;
231
    }
232
233
    protected function registerLogHandler()
234
    {
235
        $this->app->singleton('flare.logger', function ($app) {
236
            $handler = new FlareHandler($app->make('flare.client'));
237
238
            $logLevelString = config('logging.channels.flare.level', 'error');
239
240
            $logLevel = $this->getLogLevel($logLevelString);
241
242
            $handler->setMinimumReportLogLevel($logLevel);
243
244
            $logger = new Logger('Flare');
245
            $logger->pushHandler($handler);
246
247
            return $logger;
248
        });
249
250
        if ($this->app['log'] instanceof LogManager) {
251
            Log::extend('flare', function ($app) {
252
                return $app['flare.logger'];
253
            });
254
        } else {
255
            $this->bindLogListener();
256
        }
257
258
        return $this;
259
    }
260
261
    protected function getLogLevel(string $logLevelString): int
262
    {
263
        $logLevel = Logger::getLevels()[strtoupper($logLevelString)] ?? null;
264
265
        if (! $logLevel) {
266
            throw InvalidConfig::invalidLogLevel($logLevelString);
267
        }
268
269
        return $logLevel;
270
    }
271
272
    protected function registerLogRecorder()
273
    {
274
        $logCollector = $this->app->make(LogRecorder::class);
275
276
        $this->app->singleton(LogRecorder::class);
277
278
        $this->app->instance(LogRecorder::class, $logCollector);
279
280
        return $this;
281
    }
282
283
    protected function registerDumpCollector()
284
    {
285
        $dumpCollector = $this->app->make(DumpRecorder::class);
286
287
        $this->app->singleton(DumpRecorder::class);
288
289
        $this->app->instance(DumpRecorder::class, $dumpCollector);
290
291
        return $this;
292
    }
293
294
    protected function registerCommands()
295
    {
296
        $this->app->bind('command.flare:test', TestCommand::class);
297
        $this->app->bind('command.make:solution', SolutionMakeCommand::class);
298
299
        if ($this->app['config']->get('flare.key')) {
300
            $this->commands(['command.flare:test']);
301
        }
302
303
        if ($this->app['config']->get('ignition.register_commands', false)) {
304
            $this->commands(['command.make:solution']);
305
        }
306
307
        return $this;
308
    }
309
310
    protected function registerQueryRecorder()
311
    {
312
        $queryCollector = $this->app->make(QueryRecorder::class);
313
314
        $this->app->singleton(QueryRecorder::class);
315
316
        $this->app->instance(QueryRecorder::class, $queryCollector);
317
318
        return $this;
319
    }
320
321
    protected function registerBuiltInMiddleware()
322
    {
323
        $middleware = collect([
324
            SetNotifierName::class,
325
            AddEnvironmentInformation::class,
326
            AddLogs::class,
327
            AddDumps::class,
328
            AddQueries::class,
329
            AddSolutions::class,
330
        ])
331
        ->map(function (string $middlewareClass) {
332
            return $this->app->make($middlewareClass);
333
        });
334
335
        if (config('flare.reporting.collect_git_information')) {
336
            $middleware[] = (new AddGitInformation());
337
        }
338
339
        if (! is_null(config('flare.reporting.grouping_type'))) {
340
            $middleware[] = new CustomizeGrouping(config('flare.reporting.grouping_type'));
341
        }
342
343
        foreach ($middleware as $singleMiddleware) {
344
            $this->app->get('flare.client')->registerMiddleware($singleMiddleware);
345
        }
346
347
        return $this;
348
    }
349
350
    protected function getDefaultSolutions(): array
351
    {
352
        return [
353
            IncorrectValetDbCredentialsSolutionProvider::class,
354
            MissingAppKeySolutionProvider::class,
355
            DefaultDbNameSolutionProvider::class,
356
            BadMethodCallSolutionProvider::class,
357
            TableNotFoundSolutionProvider::class,
358
            MissingImportSolutionProvider::class,
359
            MissingPackageSolutionProvider::class,
360
            InvalidRouteActionSolutionProvider::class,
361
            ViewNotFoundSolutionProvider::class,
362
            UndefinedVariableSolutionProvider::class,
363
            MergeConflictSolutionProvider::class,
364
            RunningLaravelDuskInProductionProvider::class,
365
            MissingColumnSolutionProvider::class,
366
            UnknownValidationSolutionProvider::class,
367
        ];
368
    }
369
370
    protected function hasCustomViewEnginesRegistered()
371
    {
372
        $resolver = $this->app->make('view.engine.resolver');
373
374
        if (! $resolver->resolve('php') instanceof LaravelPhpEngine) {
375
            return false;
376
        }
377
378
        if (! $resolver->resolve('blade') instanceof LaravelCompilerEngine) {
379
            return false;
380
        }
381
382
        return true;
383
    }
384
385
    protected function bindLogListener()
386
    {
387
        $this->app['log']->listen(function (MessageLogged $messageLogged) {
388
            if (config('flare.key')) {
389
                try {
390
                    $this->app['flare.logger']->log(
391
                        $messageLogged->level,
392
                        $messageLogged->message,
393
                        $messageLogged->context
394
                    );
395
                } catch (Exception $exception) {
0 ignored issues
show
Bug introduced by
The class Facade\Ignition\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
396
                    return;
397
                }
398
            }
399
        });
400
    }
401
402
    protected function getConfigFileLocation(): ?string
403
    {
404
        $configFullPath = base_path().DIRECTORY_SEPARATOR.'.ignition';
405
406
        if (file_exists($configFullPath)) {
407
            return $configFullPath;
408
        }
409
410
        $configFullPath = Arr::get($_SERVER, 'HOME', '').DIRECTORY_SEPARATOR.'.ignition';
411
412
        if (file_exists($configFullPath)) {
413
            return $configFullPath;
414
        }
415
416
        return null;
417
    }
418
419
    protected function setupQueue(QueueManager $queue)
420
    {
421
        $queue->looping(function () {
422
            $this->app->get('flare.client')->reset();
423
424
            if (config('flare.reporting.report_queries')) {
425
                $this->app->make(QueryRecorder::class)->reset();
426
            }
427
428
            $this->app->make(LogRecorder::class)->reset();
429
430
            $this->app->make(DumpRecorder::class)->reset();
431
        });
432
    }
433
}
434