-
-
Notifications
You must be signed in to change notification settings - Fork 367
/
ServicesProvider.php
executable file
·657 lines (545 loc) · 24.7 KB
/
ServicesProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
<?php
/*
* UserFrosting (http://www.userfrosting.com)
*
* @link https://github.com/userfrosting/UserFrosting
* @copyright Copyright (c) 2019 Alexander Weissman
* @license https://github.com/userfrosting/UserFrosting/blob/master/LICENSE.md (MIT License)
*/
namespace UserFrosting\Sprinkle\Core\ServicesProvider;
use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
use Illuminate\Container\Container;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Events\Dispatcher;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Session\DatabaseSessionHandler;
use Illuminate\Session\FileSessionHandler;
use Illuminate\Session\NullSessionHandler;
use League\FactoryMuffin\FactoryMuffin;
use League\FactoryMuffin\Faker\Facade as Faker;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Container\ContainerInterface;
use Slim\Views\Twig;
use Slim\Views\TwigExtension;
use Twig\Extension\DebugExtension;
use UserFrosting\Assets\AssetBundles\GulpBundleAssetsCompiledBundles as CompiledAssetBundles;
use UserFrosting\Assets\AssetLoader;
use UserFrosting\Assets\Assets;
use UserFrosting\Cache\MemcachedStore;
use UserFrosting\Cache\RedisStore;
use UserFrosting\Cache\TaggableFileStore;
use UserFrosting\Config\ConfigPathBuilder;
use UserFrosting\Session\Session;
use UserFrosting\Sprinkle\Core\Alert\CacheAlertStream;
use UserFrosting\Sprinkle\Core\Alert\SessionAlertStream;
use UserFrosting\Sprinkle\Core\Csrf\SlimCsrfProvider;
use UserFrosting\Sprinkle\Core\Database\Migrator\DatabaseMigrationRepository;
use UserFrosting\Sprinkle\Core\Database\Migrator\MigrationLocator;
use UserFrosting\Sprinkle\Core\Database\Migrator\Migrator;
use UserFrosting\Sprinkle\Core\Database\Seeder\Seeder;
use UserFrosting\Sprinkle\Core\Error\ExceptionHandlerManager;
use UserFrosting\Sprinkle\Core\Error\Handler\NotFoundExceptionHandler;
use UserFrosting\Sprinkle\Core\Filesystem\FilesystemManager;
use UserFrosting\Sprinkle\Core\Log\MixedFormatter;
use UserFrosting\Sprinkle\Core\Mail\Mailer;
use UserFrosting\Sprinkle\Core\Router;
use UserFrosting\Sprinkle\Core\Throttle\Throttler;
use UserFrosting\Sprinkle\Core\Throttle\ThrottleRule;
use UserFrosting\Sprinkle\Core\Twig\CoreExtension;
use UserFrosting\Sprinkle\Core\Util\CheckEnvironment;
use UserFrosting\Sprinkle\Core\Util\ClassMapper;
use UserFrosting\Sprinkle\Core\Util\RawAssetBundles;
use UserFrosting\Support\Exception\NotFoundException;
use UserFrosting\Support\Repository\Loader\ArrayFileLoader;
use UserFrosting\Support\Repository\Repository;
/**
* UserFrosting core services provider.
*
* Registers core services for UserFrosting, such as config, database, asset manager, translator, etc.
*
* @author Alex Weissman (https://alexanderweissman.com)
*/
class ServicesProvider
{
/**
* Register UserFrosting's core services.
*
* @param ContainerInterface $container A DI container implementing ArrayAccess and psr-container.
*/
public function register(ContainerInterface $container)
{
/*
* Flash messaging service.
*
* Persists error/success messages between requests in the session.
*
* @throws \Exception If alert storage handler is not supported
* @return \UserFrosting\Sprinkle\Core\Alert\AlertStream
*/
$container['alerts'] = function ($c) {
$config = $c->config;
if ($config['alert.storage'] == 'cache') {
return new CacheAlertStream($config['alert.key'], $c->translator, $c->cache, $c->session->getId());
} elseif ($config['alert.storage'] == 'session') {
return new SessionAlertStream($config['alert.key'], $c->translator, $c->session);
} else {
throw new \Exception("Bad alert storage handler type '{$config['alert.storage']}' specified in configuration file.");
}
};
/*
* Asset loader service
*
* Loads assets from a specified relative location.
* Assets are Javascript, CSS, image, and other files used by your site.
* This implementation is a temporary hack until Assets can be refactored.
*
* @return \UserFrosting\Assets\AssetLoader
*/
$container['assetLoader'] = function ($c) {
return new AssetLoader($c->assets);
};
/*
* Asset manager service.
*
* Loads raw or compiled asset information from your bundle.config.json schema file.
* Assets are Javascript, CSS, image, and other files used by your site.
*
* @return \UserFrosting\Assets\Assets
*/
$container['assets'] = function ($c) {
$config = $c->config;
$locator = $c->locator;
// Load asset schema
if ($config['assets.use_raw']) {
// Register sprinkle assets stream, plus vendor assets in shared streams
$locator->registerStream('assets', 'vendor', \UserFrosting\NPM_ASSET_DIR, true);
$locator->registerStream('assets', 'vendor', \UserFrosting\BROWSERIFIED_ASSET_DIR, true);
$locator->registerStream('assets', 'vendor', \UserFrosting\BOWER_ASSET_DIR, true);
$locator->registerStream('assets', '', \UserFrosting\ASSET_DIR_NAME);
$baseUrl = $config['site.uri.public'] . '/' . $config['assets.raw.path'];
$assets = new Assets($locator, 'assets', $baseUrl);
// Load raw asset bundles for each Sprinkle.
// Retrieve locations of raw asset bundle schemas that exist.
$bundleSchemas = array_reverse($locator->findResources('sprinkles://' . $config['assets.raw.schema']));
// Load asset bundle schemas that exist.
if (array_key_exists(0, $bundleSchemas)) {
$bundles = new RawAssetBundles(array_shift($bundleSchemas));
foreach ($bundleSchemas as $bundleSchema) {
$bundles->extend($bundleSchema);
}
// Add bundles to asset manager.
$assets->addAssetBundles($bundles);
}
} else {
// Register compiled assets stream in public folder + alias for vendor ones + build stream for CompiledAssetBundles
$locator->registerStream('assets', '', \UserFrosting\PUBLIC_DIR_NAME . '/' . \UserFrosting\ASSET_DIR_NAME, true);
$locator->registerStream('assets', 'vendor', \UserFrosting\PUBLIC_DIR_NAME . '/' . \UserFrosting\ASSET_DIR_NAME, true);
$locator->registerStream('build', '', \UserFrosting\BUILD_DIR_NAME, true);
$baseUrl = $config['site.uri.public'] . '/' . $config['assets.compiled.path'];
$assets = new Assets($locator, 'assets', $baseUrl);
// Load compiled asset bundle.
$path = $locator->findResource('build://' . $config['assets.compiled.schema'], true, true);
$bundles = new CompiledAssetBundles($path);
$assets->addAssetBundles($bundles);
}
return $assets;
};
/*
* Cache service.
*
* @throws \Exception If cache handler is not supported
* @return \Illuminate\Cache\Repository
*/
$container['cache'] = function ($c) {
$config = $c->config;
if ($config['cache.driver'] == 'file') {
$path = $c->locator->findResource('cache://', true, true);
$cacheStore = new TaggableFileStore($path);
} elseif ($config['cache.driver'] == 'memcached') {
// We need to inject the prefix in the memcached config
$config = array_merge($config['cache.memcached'], ['prefix' => $config['cache.prefix']]);
$cacheStore = new MemcachedStore($config);
} elseif ($config['cache.driver'] == 'redis') {
// We need to inject the prefix in the redis config
$config = array_merge($config['cache.redis'], ['prefix' => $config['cache.prefix']]);
$cacheStore = new RedisStore($config);
} else {
throw new \Exception("Bad cache store type '{$config['cache.driver']}' specified in configuration file.");
}
return $cacheStore->instance();
};
/*
* Middleware to check environment.
*
* @todo We should cache the results of this, the first time that it succeeds.
*
* @return \UserFrosting\Sprinkle\Core\Util\CheckEnvironment
*/
$container['checkEnvironment'] = function ($c) {
return new CheckEnvironment($c->view, $c->locator, $c->cache);
};
/*
* Class mapper.
*
* Creates an abstraction on top of class names to allow extending them in sprinkles.
*
* @return \UserFrosting\Sprinkle\Core\Util\ClassMapper
*/
$container['classMapper'] = function ($c) {
$classMapper = new ClassMapper();
$classMapper->setClassMapping('query_builder', 'UserFrosting\Sprinkle\Core\Database\Builder');
$classMapper->setClassMapping('eloquent_builder', 'UserFrosting\Sprinkle\Core\Database\EloquentBuilder');
$classMapper->setClassMapping('throttle', 'UserFrosting\Sprinkle\Core\Database\Models\Throttle');
return $classMapper;
};
/*
* Site config service (separate from Slim settings).
*
* Will attempt to automatically determine which config file(s) to use based on the value of the UF_MODE environment variable.
*
* @return \UserFrosting\Support\Repository\Repository
*/
$container['config'] = function ($c) {
// Grab any relevant dotenv variables from the .env file
try {
$dotenv = Dotenv::createImmutable(\UserFrosting\APP_DIR);
$dotenv->load();
} catch (InvalidPathException $e) {
// Skip loading the environment config file if it doesn't exist.
}
// Get configuration mode from environment
$mode = env('UF_MODE', '');
// Construct and load config repository
$builder = new ConfigPathBuilder($c->locator, 'config://');
$loader = new ArrayFileLoader($builder->buildPaths($mode));
$config = new Repository($loader->load());
// Construct base url from components, if not explicitly specified
if (!isset($config['site.uri.public'])) {
$uri = $c->request->getUri();
// Slim\Http\Uri likes to add trailing slashes when the path is empty, so this fixes that.
$config['site.uri.public'] = trim($uri->getBaseUrl(), '/');
}
// Hacky fix to prevent sessions from being hit too much: ignore CSRF middleware for requests for raw assets ;-)
// See https://github.com/laravel/framework/issues/8172#issuecomment-99112012 for more information on why it's bad to hit Laravel sessions multiple times in rapid succession.
$csrfBlacklist = $config['csrf.blacklist'];
$csrfBlacklist['^/' . $config['assets.raw.path']] = [
'GET',
];
$config->set('csrf.blacklist', $csrfBlacklist);
return $config;
};
/*
* Initialize CSRF guard middleware.
*
* @see https://github.com/slimphp/Slim-Csrf
* @throws \UserFrosting\Support\Exception\BadRequestException
* @return \Slim\Csrf\Guard
*/
$container['csrf'] = function ($c) {
return SlimCsrfProvider::setupService($c);
};
/*
* Initialize Eloquent Capsule, which provides the database layer for UF.
*
* @todo construct the individual objects rather than using the facade
* @return \Illuminate\Database\Capsule\Manager
*/
$container['db'] = function ($c) {
$config = $c->config;
$capsule = new Capsule();
foreach ($config['db'] as $name => $dbConfig) {
$capsule->addConnection($dbConfig, $name);
}
$queryEventDispatcher = new Dispatcher(new Container());
$capsule->setEventDispatcher($queryEventDispatcher);
// Register as global connection
$capsule->setAsGlobal();
// Start Eloquent
$capsule->bootEloquent();
if ($config['debug.queries']) {
$logger = $c->queryLogger;
foreach ($config['db'] as $name => $dbConfig) {
$capsule->connection($name)->enableQueryLog();
}
// Register listener
$queryEventDispatcher->listen(QueryExecuted::class, function ($query) use ($logger) {
$logger->debug("Query executed on database [{$query->connectionName}]:", [
'query' => $query->sql,
'bindings' => $query->bindings,
'time' => $query->time . ' ms',
]);
});
}
return $capsule;
};
/*
* Debug logging with Monolog.
*
* Extend this service to push additional handlers onto the 'debug' log stack.
*
* @return \Monolog\Logger
*/
$container['debugLogger'] = function ($c) {
$logger = new Logger('debug');
$logFile = $c->locator->findResource('log://userfrosting.log', true, true);
$handler = new StreamHandler($logFile);
$formatter = new MixedFormatter(null, null, true);
$handler->setFormatter($formatter);
$logger->pushHandler($handler);
return $logger;
};
/*
* Custom error-handler for recoverable errors.
*
* @return \UserFrosting\Sprinkle\Core\Error\ExceptionHandlerManager
*/
$container['errorHandler'] = function ($c) {
$settings = $c->settings;
$handler = new ExceptionHandlerManager($c, $settings['displayErrorDetails']);
// Register the base HttpExceptionHandler.
$handler->registerHandler('\UserFrosting\Support\Exception\HttpException', '\UserFrosting\Sprinkle\Core\Error\Handler\HttpExceptionHandler');
// Register the NotFoundExceptionHandler.
$handler->registerHandler('\UserFrosting\Support\Exception\NotFoundException', '\UserFrosting\Sprinkle\Core\Error\Handler\NotFoundExceptionHandler');
// Register the PhpMailerExceptionHandler.
$handler->registerHandler('\phpmailerException', '\UserFrosting\Sprinkle\Core\Error\Handler\PhpMailerExceptionHandler');
return $handler;
};
/*
* Error logging with Monolog.
*
* Extend this service to push additional handlers onto the 'error' log stack.
*
* @return \Monolog\Logger
*/
$container['errorLogger'] = function ($c) {
$log = new Logger('errors');
$logFile = $c->locator->findResource('log://userfrosting.log', true, true);
$handler = new StreamHandler($logFile, Logger::WARNING);
$formatter = new LineFormatter(null, null, true);
$handler->setFormatter($formatter);
$log->pushHandler($handler);
return $log;
};
/*
* Factory service with FactoryMuffin.
*
* Provide access to factories for the rapid creation of objects for the purpose of testing
*
* @return \League\FactoryMuffin\FactoryMuffin
*/
$container['factory'] = function ($c) {
// Get the path of all of the sprinkle's factories
$factoriesPath = $c->locator->findResources('factories://', true);
// Create a new Factory Muffin instance
$fm = new FactoryMuffin();
// Load all of the model definitions
$fm->loadFactories($factoriesPath);
// Set the locale. Could be the config one, but for testing English should do
Faker::setLocale('en_EN');
return $fm;
};
/*
* Filesystem Service
* @return \UserFrosting\Sprinkle\Core\Filesystem\FilesystemManager
*/
$container['filesystem'] = function ($c) {
return new FilesystemManager($c->config);
};
/*
* Mail service.
*
* @return \UserFrosting\Sprinkle\Core\Mail\Mailer
*/
$container['mailer'] = function ($c) {
$mailer = new Mailer($c->mailLogger, $c->config['mail']);
// Use UF debug settings to override any service-specific log settings.
if (!$c->config['debug.smtp']) {
$mailer->getPhpMailer()->SMTPDebug = 0;
}
return $mailer;
};
/*
* Mail logging service.
*
* PHPMailer will use this to log SMTP activity.
* Extend this service to push additional handlers onto the 'mail' log stack.
*
* @return \Monolog\Logger
*/
$container['mailLogger'] = function ($c) {
$log = new Logger('mail');
$logFile = $c->locator->findResource('log://userfrosting.log', true, true);
$handler = new StreamHandler($logFile);
$formatter = new LineFormatter(null, null, true);
$handler->setFormatter($formatter);
$log->pushHandler($handler);
return $log;
};
/*
* Migrator service.
*
* This service handles database migration operations
*
* @return \UserFrosting\Sprinkle\Core\Database\Migrator\Migrator
*/
$container['migrator'] = function ($c) {
$migrator = new Migrator(
$c->db,
new DatabaseMigrationRepository($c->db, $c->config['migrations.repository_table']),
new MigrationLocator($c->locator)
);
// Make sure repository exist
if (!$migrator->repositoryExists()) {
$migrator->getRepository()->createRepository();
}
return $migrator;
};
/*
* Error-handler for 404 errors. Notice that we manually create a UserFrosting NotFoundException,
* and a NotFoundExceptionHandler. This lets us pass through to the UF error handling system.
*
* @return callable
*/
$container['notFoundHandler'] = function ($c) {
return function ($request, $response) use ($c) {
$exception = new NotFoundException();
$handler = new NotFoundExceptionHandler($c, $request, $response, $exception, $c->settings['displayErrorDetails']);
return $handler->handle();
};
};
/*
* Error-handler for PHP runtime errors. Notice that we just pass this through to our general-purpose
* error-handling service.
*
* @return \UserFrosting\Sprinkle\Core\Error\ExceptionHandlerManager
*/
$container['phpErrorHandler'] = function ($c) {
return $c->errorHandler;
};
/*
* Laravel query logging with Monolog.
*
* Extend this service to push additional handlers onto the 'query' log stack.
*
* @return \Monolog\Logger
*/
$container['queryLogger'] = function ($c) {
$logger = new Logger('query');
$logFile = $c->locator->findResource('log://userfrosting.log', true, true);
$handler = new StreamHandler($logFile);
$formatter = new MixedFormatter(null, null, true);
$handler->setFormatter($formatter);
$logger->pushHandler($handler);
return $logger;
};
/*
* Override Slim's default router with the UF router.
*
* @return \UserFrosting\Sprinkle\Core\Router
*/
$container['router'] = function ($c) {
$routerCacheFile = false;
if (isset($c->config['settings.routerCacheFile'])) {
$filename = $c->config['settings.routerCacheFile'];
$routerCacheFile = $c->locator->findResource("cache://$filename", true, true);
}
return (new Router())->setCacheFile($routerCacheFile);
};
/*
* Return an instance of the database seeder
*
* @return \UserFrosting\Sprinkle\Core\Database\Seeder\Seeder
*/
$container['seeder'] = function ($c) {
return new Seeder($c);
};
/*
* Start the PHP session, with the name and parameters specified in the configuration file.
*
* @throws \Exception
* @return \UserFrosting\Session\Session
*/
$container['session'] = function ($c) {
$config = $c->config;
// Create appropriate handler based on config
if ($config['session.handler'] == 'file') {
$fs = new Filesystem();
$handler = new FileSessionHandler($fs, $c->locator->findResource('session://'), $config['session.minutes']);
} elseif ($config['session.handler'] == 'database') {
$connection = $c->db->connection();
// Table must exist, otherwise an exception will be thrown
$handler = new DatabaseSessionHandler($connection, $config['session.database.table'], $config['session.minutes']);
} elseif ($config['session.handler'] == 'array') {
$handler = new NullSessionHandler();
} else {
throw new \Exception("Bad session handler type '{$config['session.handler']}' specified in configuration file.");
}
// Create, start and return a new wrapper for $_SESSION
$session = new Session($handler, $config['session']);
$session->start();
return $session;
};
/*
* Request throttler.
*
* Throttles (rate-limits) requests of a predefined type, with rules defined in site config.
*
* @return \UserFrosting\Sprinkle\Core\Throttle\Throttler
*/
$container['throttler'] = function ($c) {
$throttler = new Throttler($c->classMapper);
$config = $c->config;
if ($config->has('throttles') && ($config['throttles'] !== null)) {
foreach ($config['throttles'] as $type => $rule) {
if ($rule) {
$throttleRule = new ThrottleRule($rule['method'], $rule['interval'], $rule['delays']);
$throttler->addThrottleRule($type, $throttleRule);
} else {
$throttler->addThrottleRule($type, null);
}
}
}
return $throttler;
};
/*
* Set up Twig as the view, adding template paths for all sprinkles and the Slim Twig extension.
*
* Also adds the UserFrosting core Twig extension, which provides additional functions, filters, global variables, etc.
*
* @return \Slim\Views\Twig
*/
$container['view'] = function ($c) {
/** @var \UserFrosting\UniformResourceLocator\ResourceLocator $locator */
$locator = $c->locator;
$templatePaths = $locator->getResources('templates://');
$view = new Twig(array_map('strval', $templatePaths));
$loader = $view->getLoader();
// Add Sprinkles' templates namespaces
foreach (array_reverse($templatePaths) as $templateResource) {
$loader->addPath($templateResource->getAbsolutePath(), $templateResource->getLocation()->getName());
}
$twig = $view->getEnvironment();
if ($c->config['cache.twig']) {
$twig->setCache($c->locator->findResource('cache://twig', true, true));
}
if ($c->config['debug.twig']) {
$twig->enableDebug();
$view->addExtension(new DebugExtension());
}
// Register the Slim extension with Twig
$slimExtension = new TwigExtension(
$c->router,
$c->request->getUri()
);
$view->addExtension($slimExtension);
// Register the core UF extension with Twig
$coreExtension = new CoreExtension($c);
$view->addExtension($coreExtension);
return $view;
};
}
}