Test Failed
Push — master ( bfe357...41d8e8 )
by Antonio Carlos
25:24
created

ServiceProvider::instantiateService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PragmaRX\Health;
4
5
use Event;
6
use Artisan;
7
use PragmaRX\Yaml\Package\Yaml;
8
use PragmaRX\Health\Support\Cache;
9
use Illuminate\Console\Scheduling\Schedule;
10
use PragmaRX\Health\Support\ResourceLoader;
11
use PragmaRX\Health\Support\Traits\Routing;
12
use PragmaRX\Health\Events\RaiseHealthIssue;
13
use PragmaRX\Health\Support\ResourceChecker;
14
use PragmaRX\Health\Listeners\NotifyHealthIssue;
15
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
16
17
class ServiceProvider extends IlluminateServiceProvider
18
{
19
    use Routing;
20
21
    /**
22
     * The application instance.
23
     *
24
     * @var \Illuminate\Foundation\Application
25
     */
26
    protected $app;
27
28
    /**
29
     * Resource loader instance.
30
     *
31
     * @var
32
     */
33
    protected $resourceLoader;
34
35
    /**
36
     * The health service.
37
     *
38
     * @var
39
     */
40
    private $healthService;
41
42
    /**
43
     * All artisan commands.
44
     *
45
     * @var
46
     */
47
    private $commands;
48
49
    /**
50
     * The router.
51
     *
52
     * @var
53
     */
54
    private $router;
55
56
    /**
57
     * Cache closure.
58
     *
59
     * @var
60
     */
61
    private $cacheClosure;
62
63
    /**
64
     * Resource checker closure.
65
     *
66
     * @var
67
     */
68
    private $resourceCheckerClosure;
69
70
    /**
71
     * Health service closure.
72
     *
73
     * @var
74
     */
75
    private $healthServiceClosure;
76
77
    /**
78
     * Configure package paths.
79
     */
80
    private function configurePaths()
81
    {
82
        $this->publishes(
83
            [
84
                __DIR__ . '/config/health.php' => config_path(
85
                    'health/config.php'
86
                ),
87
                __DIR__ . '/config/resources/' => config_path(
88
                    'health/resources/'
89
                ),
90
            ],
91
            'config'
92
        );
93
94
        $this->publishes(
95
            [
96
                __DIR__ . '/resources/views/' => resource_path(
97
                    'views/vendor/pragmarx/health/'
98
                ),
99
            ],
100
            'views'
101
        );
102
103
        $this->publishes(
104
            [
105
                __DIR__ . '/database/migrations/' => database_path(
106
                    'migrations'
107
                ),
108
            ],
109
            'migrations'
110
        );
111
    }
112
113
    /**
114
     * Configure package folder views.
115
     */
116
    private function configureViews()
117
    {
118
        $this->loadViewsFrom(
119
            realpath(__DIR__ . '/resources/views'),
120
            'pragmarx/health'
121
        );
122
    }
123
124
    /**
125
     * Create health service.
126
     */
127
    private function createHealthService()
128
    {
129
        $resourceChecker = call_user_func($this->resourceCheckerClosure);
130
131
        $cache = call_user_func($this->cacheClosure);
132
133
        $this->healthServiceClosure = function () use (
134
            $resourceChecker,
135
            $cache
136
        ) {
137
            return $this->instantiateService($resourceChecker, $cache);
138
        };
139
140
        $this->healthService = call_user_func($this->healthServiceClosure);
141
    }
142
143
    /**
144
     * Create resource checker.
145
     */
146
    private function createResourceChecker()
147
    {
148
        $this->resourceLoader = new ResourceLoader(new Yaml());
149
150
        $this->cacheClosure = $this->getCacheClosure();
151
152
        $this->resourceCheckerClosure = $this->getResourceCheckerClosure(
153
            $this->resourceLoader,
154
            call_user_func($this->cacheClosure)
155
        );
156
    }
157
158
    /**
159
     * Get the cache closure for instantiation.
160
     *
161
     * @return \Closure
162
     */
163
    private function getCacheClosure()
164
    {
165
        $cacheClosure = function () {
166
            return new Cache();
167
        };
168
169
        return $cacheClosure;
170
    }
171
172
    /**
173
     * Return the health service.
174
     *
175
     * @return mixed
176
     */
177
    public function getHealthService()
178
    {
179
        return $this->healthService;
180
    }
181
182
    /**
183
     * Get the resource checker closure for instantiation.
184
     *
185
     * @param $resourceLoader
186
     * @param $cache
187
     * @return \Closure
188
     */
189
    private function getResourceCheckerClosure($resourceLoader, $cache)
190
    {
191
        $resourceCheckerInstance = function () use ($resourceLoader, $cache) {
192
            return new ResourceChecker($resourceLoader, $cache);
193
        };
194
195
        return $resourceCheckerInstance;
196
    }
197
198
    /**
199
     * Get the list of routes.
200
     *
201
     * @return array
202
     */
203
    private function getRoutes()
204
    {
205
        return config('health.routes.list');
206
    }
207
208
    /**
209
     * Instantiate commands.
210
     *
211
     * @return \Illuminate\Foundation\Application|mixed
212
     */
213
    private function instantiateCommands()
214
    {
215
        return $this->commands = instantiate(Commands::class, [
216
            $this->healthService,
217
        ]);
218
    }
219
220
    /**
221
     * Instantiate the main service.
222
     *
223
     * @param $resourceChecker
224
     * @param $cache
225
     * @return Service
226
     */
227
    private function instantiateService($resourceChecker, $cache)
228
    {
229
        return $this->healthService = new Service($resourceChecker, $cache);
230
    }
231
232
    /**
233
     * Merge configuration.
234
     */
235
    private function mergeConfig()
236
    {
237
        if (file_exists(config_path('/health/config.php'))) {
238
            $this->mergeConfigFrom(config_path('/health/config.php'), 'health');
239
        }
240
241
        $this->mergeConfigFrom(__DIR__ . '/config/health.php', 'health');
242
    }
243
244
    /**
245
     * Register any application services.
246
     *
247
     * @return void
248
     */
249
    public function register()
250
    {
251
        $this->mergeConfig();
252
253
        $this->configureViews();
254
255
        $this->configurePaths();
256
257
        $this->registerServices();
258
259
        $this->registerRoutes();
260
261
        $this->registerTasks();
262
263
        $this->registerEventListeners();
264
265
        $this->registerConsoleCommands();
266
    }
267
268
    private function registerResourcesRoutes()
269
    {
270
        collect($this->resourceLoader->getResources())->each(function ($item) {
271
            if (isset($item['routes'])) {
272
                collect($item['routes'])->each(function ($route, $key) {
273
                    $this->registerRoute($route, $key);
274
                });
275
            }
276
        });
277
    }
278
279
    /**
280
     * Register console commands.
281
     */
282
    private function registerConsoleCommands()
283
    {
284
        $commands = $this->commands;
285
286
        Artisan::command('health:panel', function () use ($commands) {
287
            $commands->panel($this);
288
        })->describe('Show all resources and their current health states.');
289
290
        Artisan::command('health:check', function () use ($commands) {
291
            $commands->check($this);
292
        })->describe('Check resources health and send error notifications.');
293
294
        Artisan::command('health:export', function () use ($commands) {
295
            $commands->export($this);
296
        })->describe('Export "array" resources to .yml files');
297
298
        Artisan::command('health:publish', function () use ($commands) {
299
            $commands->publish($this);
300
        })->describe('Publish all .yml resouces files to config directory.');
301
    }
302
303
    /**
304
     * Register event listeners.
305
     */
306
    private function registerEventListeners()
307
    {
308
        Event::listen(RaiseHealthIssue::class, NotifyHealthIssue::class);
309
    }
310
311
    /**
312
     * Register routes.
313
     */
314
    private function registerRoutes()
315
    {
316
        collect($routes = $this->getRoutes())->each(function ($route) {
317
            $this->registerRoute($route);
318
        });
319
320
        $this->registerResourcesRoutes();
321
    }
322
323
    /**
324
     * Register service.
325
     */
326
    private function registerServices()
327
    {
328
        $this->createServices();
329
330
        $this->app->singleton('pragmarx.health.cache', $this->cacheClosure);
331
332
        $this->app->singleton(
333
            'pragmarx.health.resource.checker',
334
            $this->resourceCheckerClosure
335
        );
336
337
        $this->app->singleton('pragmarx.health', $this->healthServiceClosure);
338
339
        $this->app->singleton(
340
            'pragmarx.health.commands',
341
            $this->instantiateCommands()
342
        );
343
    }
344
345
    /**
346
     * Create services.
347
     */
348
    public function createServices()
349
    {
350
        $this->createResourceChecker();
351
352
        $this->createHealthService();
353
    }
354
355
    /**
356
     * Register scheduled tasks.
357
     */
358
    private function registerTasks()
359
    {
360
        if (
361
            config('health.scheduler.enabled') &&
362
            ($frequency = config('health.scheduler.frequency')) &&
363
            config('health.notifications.enabled')
364
        ) {
365
            $scheduler = instantiate(Schedule::class);
366
367
            $scheduler
368
                ->call($this->healthService->getSilentChecker())
369
                ->$frequency();
370
        }
371
    }
372
373
    /**
374
     * Get the services provided by the provider.
375
     *
376
     * @return array
377
     */
378
    public function provides()
379
    {
380
        return [
381
            'pragmarx.health.cache',
382
            'pragmarx.health.resource.checker',
383
            'pragmarx.health',
384
            'pragmarx.health.commands',
385
        ];
386
    }
387
}
388