-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApplication.php
768 lines (657 loc) · 22.5 KB
/
Application.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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
<?php
declare(strict_types=1);
namespace Codefy\Framework;
use Codefy\Framework\Factory\FileLoggerFactory;
use Codefy\Framework\Factory\FileLoggerSmtpFactory;
use Codefy\Framework\Support\Paths;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Qubus\Config\ConfigContainer;
use Qubus\Dbal\Connection;
use Qubus\Dbal\DB;
use Qubus\Exception\Data\TypeException;
use Qubus\Exception\Exception;
use Qubus\Expressive\OrmBuilder;
use Qubus\Inheritance\InvokerAware;
use Qubus\Injector\Config\InjectorFactory;
use Qubus\Injector\Psr11\Container;
use Qubus\Injector\ServiceContainer;
use Qubus\Injector\ServiceProvider\BaseServiceProvider;
use Qubus\Injector\ServiceProvider\Bootable;
use Qubus\Injector\ServiceProvider\Serviceable;
use ReflectionException;
use function get_class;
use function is_string;
use function rtrim;
use const DIRECTORY_SEPARATOR;
/**
* @property-read ServerRequestInterface $request
* @property-read ResponseInterface $response
* @property-read \Qubus\Support\Assets $assets
* @property-read \Qubus\Mail\Mailer $mailer
* @property-read \Qubus\Http\Session\PhpSession $session
* @property-read \Qubus\Http\Session\Flash $flash
* @property-read \Qubus\EventDispatcher\EventDispatcher $event
* @property-read \Qubus\Http\Cookies\Factory\HttpCookieFactory $httpCookie
* @property-read Support\LocalStorage $localStorage
* @property-read \Qubus\Config\ConfigContainer $configContainer
*/
final class Application extends Container
{
use InvokerAware;
public const APP_VERSION = '2.0.6';
public const MIN_PHP_VERSION = '8.2';
public const DS = DIRECTORY_SEPARATOR;
public static ?Application $APP = null;
public string $charset = 'UTF-8';
public string $locale = 'en';
public string $controllerNamespace = 'App\\Infrastructure\\Http\\Controllers';
public static string $ROOT_PATH;
protected ?string $basePath = null;
protected ?string $appPath = null;
protected array $serviceProviders = [];
protected array $serviceProvidersRegistered = [];
protected array $baseMiddlewares = [];
private bool $booted = false;
private bool $hasBeenBootstrapped = false;
protected array $bootingCallbacks = [];
protected array $bootedCallbacks = [];
private array $param = [];
/**
* @throws TypeException
*/
public function __construct(array $params)
{
if (isset($params['basePath'])) {
$this->withBasePath(basePath: $params['basePath']);
}
self::$APP = $this;
self::$ROOT_PATH = $this->basePath;
parent::__construct(InjectorFactory::create(config: $this->coreAliases()));
$this->registerDefaultServiceProviders();
$this->init();
}
private function init(): void
{
$contracts = [
'request' => ServerRequestInterface::class,
'response' => ResponseInterface::class,
'assets' => \Qubus\Support\Assets::class,
'mailer' => \Qubus\Mail\Mailer::class,
'session' => \Qubus\Http\Session\PhpSession::class,
'flash' => \Qubus\Http\Session\Flash::class,
'event' => \Qubus\EventDispatcher\EventDispatcher::class,
'httpCookie' => \Qubus\Http\Cookies\Factory\HttpCookieFactory::class,
'localStorage' => Support\LocalStorage::class,
'configContainer' => \Qubus\Config\ConfigContainer::class,
];
foreach ($contracts as $property => $name) {
$this->{$property} = $this->make(name: $name);
}
Codefy::$PHP = $this;
}
/**
* FileLogger
*
* @throws ReflectionException
*/
public static function getLogger(): LoggerInterface
{
return FileLoggerFactory::getLogger();
}
/**
* FileLogger with SMTP support.
*
* @throws ReflectionException
*/
public static function getSmtpLogger(): LoggerInterface
{
return FileLoggerSmtpFactory::getLogger();
}
/**
* @throws Exception
*/
public function getDbConnection(): Connection
{
/** @var ConfigContainer $config */
$config = $this->make(name: 'codefy.config');
$connection = $config->getConfigKey(key: 'database.default');
return DB::connection([
'driver' => $config->getConfigKey(key: "database.connections.{$connection}.driver"),
'host' => $config->getConfigKey(key: "database.connections.{$connection}.host", default: 'localhost'),
'port' => $config->getConfigKey(key: "database.connections.{$connection}.port", default: 3306),
'charset' => $config->getConfigKey(key: "database.connections.{$connection}.charset", default: 'utf8mb4'),
'collation' => $config->getConfigKey(
key: "database.connections.{$connection}.collation",
default: 'utf8mb4_unicode_ci'
),
'username' => $config->getConfigKey(key: "database.connections.{$connection}.username"),
'password' => $config->getConfigKey(key: "database.connections.{$connection}.password"),
'dbname' => $config->getConfigKey(key: "database.connections.{$connection}.dbname"),
]);
}
/**
* @return OrmBuilder|null
* @throws Exception
*/
public function getDB(): ?OrmBuilder
{
return new OrmBuilder(connection: $this->getDbConnection());
}
/**
* Return the version of the Application's Framework.
*
* @return string
*/
public function version(): string
{
return Application::APP_VERSION;
}
/**
* Ensure a value or object will remain globally unique.
*
* @param string $key The value or object name
* @param callable $value The closure that defines the object
* @return void
*/
public function singleton(string $key, callable $value): void
{
$this->proxy(name: $key, callableOrMethodStr: function ($c) use ($value) {
static $object;
if (null === $object) {
$object = $value($c);
}
return $object;
});
}
/**
* @throws TypeException
*/
protected function registerDefaultServiceProviders(): void
{
foreach ([
Providers\ConfigServiceProvider::class,
Providers\FlysystemServiceProvider::class,
] as $serviceProvider
) {
$this->registerServiceProvider(serviceProvider: $serviceProvider);
}
}
public function bootstrapWith(array $bootstrappers): void
{
$this->hasBeenBootstrapped = true;
foreach ($bootstrappers as $bootstrapper) {
$this->make(name: \Qubus\EventDispatcher\EventDispatcher::class)->dispatch("bootstrapping.{$bootstrapper}");
$this->make(name: $bootstrapper)->bootstrap($this);
$this->make(name: \Qubus\EventDispatcher\EventDispatcher::class)->dispatch("bootstrapped.{$bootstrapper}");
}
}
public function getContainer(): ServiceContainer|ContainerInterface
{
return $this;
}
public function setBoot(bool $bool = false): void
{
$this->booted = $bool;
}
public function isBooted(): bool
{
return $this->booted;
}
/**
* @return void
* @throws TypeException
*/
public function boot(): void
{
if ($this->booted) {
return;
}
// Once the application has booted we will also fire some "booted" callbacks
// for any listeners that need to do work after this initial booting gets
// finished. This is useful when ordering the boot-up processes we run.
$this->fireAppCallbacks($this->bootingCallbacks);
array_walk($this->serviceProviders, function ($p) {
$this->bootServiceProvider(provider: $p);
});
$this->booted = true;
$this->fireAppCallbacks($this->bootedCallbacks);
}
/**
* Force register a service provider with the application.
*
* @param string|Serviceable|Bootable $provider
* @return Serviceable|Bootable
* @throws TypeException
*/
public function forceRegisterServiceProvider(string|Serviceable|Bootable $provider): Serviceable|Bootable
{
return $this->registerServiceProvider(serviceProvider: $provider, force: true);
}
/**
* Register all configured service providers via config/app.php.
*
* @return void
* @throws TypeException
* @throws Exception
*/
public function registerConfiguredServiceProviders(): void
{
/** @var ConfigContainer $config */
$config = $this->make(name: 'codefy.config');
$providers = $config->getConfigKey(key: 'app.providers');
foreach ($providers as $serviceProvider) {
$this->registerServiceProvider(serviceProvider: $serviceProvider);
}
}
/**
* Register a Service Provider to the application.
*
* @param string|Serviceable|Bootable $serviceProvider
* @param bool $force
* @return Serviceable|Bootable|string
* @throws TypeException
*/
public function registerServiceProvider(
string|Serviceable|Bootable $serviceProvider,
bool $force = false
): Serviceable|Bootable|string {
// If the Service Provider had already been registered, then return it.
if (($registered = $this->getRegisteredServiceProvider(provider: $serviceProvider)) && !$force) {
return $registered;
}
if (is_string(value: $serviceProvider)) {
$serviceProvider = $this->resolveServiceProvider(provider: $serviceProvider);
}
$serviceProvider->register();
$this->markServiceProviderAsRegistered(registered: $registered, serviceProvider: $serviceProvider);
// If application is booted, call the boot method on the service provider
// if it exists.
if ($this->isBooted()) {
$this->bootServiceProvider(provider: $serviceProvider);
};
return $serviceProvider;
}
/**
* Get the registered service provider instance if it exists.
*
* @param Serviceable|Bootable|string $provider
* @return string|null
*/
public function getRegisteredServiceProvider(Serviceable|Bootable|string $provider): string|null
{
return $this->serviceProviders[$provider] ?? null;
}
/**
* Forget the ServiceProvider from the application.
*
* @param string|Serviceable|Bootable $serviceProvider
* @return void
*/
public function forgetServiceProvider(string|Serviceable|Bootable $serviceProvider): void
{
$registered = is_string(value: $serviceProvider) ? $serviceProvider : get_class(object: $serviceProvider);
unset($this->serviceProviders[$registered]);
}
/**
* Resolve a service provider instance from the class name.
*
* @param string $provider
* @return BaseServiceProvider
*/
public function resolveServiceProvider(string $provider): BaseServiceProvider
{
return new $provider($this);
}
/**
* Get the service providers that have been registered.
*
* @return array
*/
public function getRegisteredProviders(): array
{
return $this->serviceProvidersRegistered;
}
/**
* Determine if the given service provider is registered.
*
* @param string $provider
* @return bool
*/
public function providerIsRegistered(string $provider): bool
{
return isset($this->serviceProvidersRegistered[$provider]);
}
/**
* Boot the given service provider.
*
* @param Serviceable|Bootable $provider
* @return void
* @throws TypeException
*/
protected function bootServiceProvider(Serviceable|Bootable $provider): void
{
if (method_exists(object_or_class: $provider, method: 'boot')) {
$this->execute(callableOrMethodStr: [$provider, 'boot']);
}
}
/**
* Register a new boot listener.
*
* @param callable $callback
* @return void
*/
public function booting(callable $callback): void
{
$this->bootingCallbacks[] = $callback;
}
/**
* Register a new "booted" listener.
*
* @param callable $callback
* @return void
*/
public function booted(callable $callback): void
{
$this->bootedCallbacks[] = $callback;
if ($this->isBooted()) {
$callback($this);
}
}
/**
* Call the booting callbacks for the application.
*
* @param callable[] $callbacks
* @return void
*/
protected function fireAppCallbacks(array &$callbacks): void
{
$index = 0;
while ($index < count($callbacks)) {
$callbacks[$index]($this);
$index++;
}
}
/**
* Mark the particular ServiceProvider as having been registered.
*
* @param string|null $registered
* @param Serviceable|Bootable $serviceProvider
* @return void
*/
protected function markServiceProviderAsRegistered(
string|null $registered,
Serviceable|Bootable $serviceProvider
): void {
$this->serviceProviders[$registered] = $serviceProvider;
$this->serviceProvidersRegistered[$registered] = true;
}
/**
* Determine if the application has been bootstrapped before.
*
* @return bool
*/
public function hasBeenBootstrapped(): bool
{
return $this->hasBeenBootstrapped;
}
/**
* Set the Application's base directory.
*
* @param string $basePath
* @return mixed
*/
public function withBasePath(string $basePath): self
{
$this->basePath = rtrim(string: $basePath, characters: '\/');
$this->bindPathsToContainer();
return $this;
}
protected function bindPathsToContainer(): void
{
$this->define(name: Paths::class, args: [
':paths' => [
'path' => $this->path(),
'base' => $this->basePath(),
'bootstrap' => $this->bootStrapPath(),
'config' => $this->configPath(),
'database' => $this->databasePath(),
'locale' => $this->localePath(),
'public' => $this->publicPath(),
'storage' => $this->storagePath(),
'resource' => $this->resourcePath(),
'view' => $this->viewPath(),
]
]);
}
/**
* Set the Application's "app" directory.
*
* @param string $appPath
* @return self
*/
public function withAppPath(string $appPath): self
{
$this->appPath = $appPath;
return $this;
}
/**
* Get the path to the application's "app" directory.
*
* @return string
*/
public function path(): string
{
return $this->appPath ?: $this->basePath . self::DS . 'app';
}
/**
* Get the Application's base directory.
*
* @return string
*/
public function basePath(): string
{
return $this->basePath;
}
/**
* Get the path to the application's "bootstrap" directory.
*
* @return string
*/
public function bootStrapPath(): string
{
return $this->basePath . self::DS . 'bootstrap';
}
/**
* Get the path to the application's "config" directory.
*
* @return string
*/
public function configPath(): string
{
return $this->basePath . self::DS . 'config';
}
/**
* Get the path to the application's "database" directory.
*
* @return string
*/
public function databasePath(): string
{
return $this->basePath . self::DS . 'database';
}
/**
* Get the path to the application's "locale" directory.
*
* @return string
*/
public function localePath(): string
{
return $this->basePath . self::DS . 'locale';
}
/**
* Get the path to the application's "public" directory.
*
* @return string
*/
public function publicPath(): string
{
return $this->basePath . self::DS . 'public';
}
/**
* Get the path to the application's "storage" directory.
*
* @return string
*/
public function storagePath(): string
{
return $this->basePath . self::DS . 'storage';
}
/**
* Get the path to the application's "resources" directory.
*
* @return string
*/
public function resourcePath(): string
{
return $this->basePath . self::DS . 'resources';
}
/**
* Get the path to the application's "view" directory.
*
* @return string
*/
public function viewPath(): string
{
return $this->basePath . self::DS . 'views';
}
/**
* @param string $locale
* @return void
*/
public function withLocale(string $locale): void
{
$this->locale = $locale;
}
/**
* @return string
*/
public function getLocale(): string
{
return $this->locale;
}
public function withControllerNamespace(string $namespace): void
{
$this->controllerNamespace = $namespace;
}
public function getControllerNamespace(): string
{
return $this->controllerNamespace;
}
public function withBaseMiddlewares(array $middlewares): void
{
$this->baseMiddlewares = $middlewares;
}
/**
* @throws Exception
*/
public function getBaseMiddlewares(): array
{
/** @var ConfigContainer $config */
$config = $this->make(name: 'codefy.config');
return array_merge($config->getConfigKey(key: 'app.base_middlewares'), $this->baseMiddlewares);
}
public function isRunningInConsole(): bool
{
return php_sapi_name() === 'cli' || php_sapi_name() == 'phpdbg';
}
/**
* Determine if the application is running with debug mode enabled.
*
* @return bool
* @throws Exception
*/
public function hasDebugModeEnabled(): bool
{
/** @var ConfigContainer $config */
$config = $this->make(name: 'codefy.config');
if ($config->getConfigKey(key: 'app.debug') === 'true') {
return true;
}
return false;
}
protected function coreAliases(): array
{
return [
self::SHARED_ALIASES => [
\Psr\Container\ContainerInterface::class => self::class,
\Qubus\Injector\ServiceContainer::class => self::class,
\Psr\Http\Message\ServerRequestInterface::class => \Qubus\Http\ServerRequest::class,
\Psr\Http\Message\ServerRequestFactoryInterface::class => \Qubus\Http\ServerRequestFactory::class,
\Psr\Http\Message\RequestInterface::class => \Qubus\Http\Request::class,
\Psr\Http\Server\RequestHandlerInterface::class => \Relay\Runner::class,
\Psr\Http\Message\ResponseInterface::class => \Qubus\Http\Response::class,
\Psr\Http\Message\ResponseFactoryInterface::class => \Laminas\Diactoros\ResponseFactory::class,
\Psr\Cache\CacheItemInterface::class => \Qubus\Cache\Psr6\Item::class,
\Psr\Cache\CacheItemPoolInterface::class => \Qubus\Cache\Psr6\ItemPool::class,
\Qubus\Cache\Psr6\TaggableCacheItem::class => \Qubus\Cache\Psr6\TaggablePsr6ItemAdapter::class,
\Qubus\Cache\Psr6\TaggableCacheItemPool::class => \Qubus\Cache\Psr6\TaggablePsr6PoolAdapter::class,
\Qubus\Config\Path\Path::class => \Qubus\Config\Path\ConfigPath::class,
\Qubus\Config\ConfigContainer::class => \Qubus\Config\Collection::class,
\Qubus\EventDispatcher\EventDispatcher::class => \Qubus\EventDispatcher\Dispatcher::class,
\Qubus\Mail\Mailer::class => \Codefy\Framework\Support\CodefyMailer::class,
'mailer' => \Qubus\Mail\Mailer::class,
'dir.path' => \Codefy\Framework\Support\Paths::class,
'container' => self::class,
'codefy' => self::class,
\Qubus\Routing\Interfaces\Collector::class => \Qubus\Routing\Route\RouteCollector::class,
'router' => \Qubus\Routing\Router::class,
\Codefy\Framework\Contracts\Kernel::class => \Codefy\Framework\Http\Kernel::class,
\Codefy\Framework\Contracts\RoutingController::class => \Codefy\Framework\Http\BaseController::class,
\League\Flysystem\FilesystemOperator::class => \Qubus\FileSystem\FileSystem::class,
\League\Flysystem\FilesystemAdapter::class => \Qubus\FileSystem\Adapter\LocalFlysystemAdapter::class,
\Qubus\Cache\Adapter\CacheAdapter::class => \Qubus\Cache\Adapter\FileSystemCacheAdapter::class,
\Codefy\Framework\Scheduler\Mutex\Locker::class
=> \Codefy\Framework\Scheduler\Mutex\CacheLocker::class,
\Psr\SimpleCache\CacheInterface::class => \Qubus\Cache\Psr16\SimpleCache::class,
\Qubus\Http\Session\PhpSession::class => \Qubus\Http\Session\NativeSession::class,
\DateTimeInterface::class => \Qubus\Support\DateTime\QubusDateTimeImmutable::class,
\Qubus\Support\DateTime\Date::class => \Qubus\Support\DateTime\QubusDate::class,
\Symfony\Component\Console\Input\InputInterface::class
=> \Symfony\Component\Console\Input\ArgvInput::class,
\Symfony\Component\Console\Output\OutputInterface::class
=> \Symfony\Component\Console\Output\ConsoleOutput::class,
\Qubus\Http\Cookies\Factory\HttpCookieFactory::class
=> \Qubus\Http\Cookies\Factory\CookieFactory::class,
\Qubus\Http\Session\Storage\SessionStorage::class
=> \Qubus\Http\Session\Storage\SimpleCacheStorage::class,
]
];
}
public function __get(mixed $name)
{
return $this->param[$name];
}
public function __isset(mixed $name): bool
{
return isset($this->data[$name]);
}
public function __set(mixed $name, mixed $value): void
{
$this->param[$name] = $value;
}
public function __unset(mixed $name): void
{
unset($this->param[$name]);
}
public function __destruct()
{
$this->bootedCallbacks = [];
$this->bootingCallbacks = [];
$this->serviceProviders = [];
$this->serviceProvidersRegistered = [];
$this->baseMiddlewares = [];
}
}