Keep Laravel from auto-discovering nesbot/carbon so the app can boot the lazy Carbon provider instead.
99 lines
2.6 KiB
PHP
99 lines
2.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Providers;
|
|
|
|
use Carbon\Carbon;
|
|
use Carbon\CarbonImmutable;
|
|
use Carbon\CarbonInterval;
|
|
use Carbon\CarbonPeriod;
|
|
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
|
|
use Illuminate\Foundation\Events\LocaleUpdated;
|
|
use Illuminate\Support\Carbon as IlluminateCarbon;
|
|
use Illuminate\Support\Facades\Date;
|
|
use Illuminate\Support\ServiceProvider;
|
|
use Throwable;
|
|
|
|
final class LazyCarbonServiceProvider extends ServiceProvider
|
|
{
|
|
private bool $localeListenerRegistered = false;
|
|
|
|
public function register(): void
|
|
{
|
|
$registerListener = function (DispatcherContract $events): void {
|
|
if ($this->localeListenerRegistered) {
|
|
return;
|
|
}
|
|
|
|
$this->localeListenerRegistered = true;
|
|
|
|
$events->listen(
|
|
LocaleUpdated::class,
|
|
function (LocaleUpdated $event): void {
|
|
$this->synchronizeCarbonLocale($event->locale);
|
|
}
|
|
);
|
|
};
|
|
|
|
if ($this->app->resolved('events')) {
|
|
$registerListener(
|
|
$this->app->make('events')
|
|
);
|
|
|
|
return;
|
|
}
|
|
|
|
$this->app->afterResolving(
|
|
'events',
|
|
$registerListener
|
|
);
|
|
}
|
|
|
|
private function synchronizeCarbonLocale(string $locale): void
|
|
{
|
|
$fallback = (string) $this->app['config']->get(
|
|
'app.fallback_locale',
|
|
'en'
|
|
);
|
|
|
|
Carbon::setLocale($locale);
|
|
CarbonImmutable::setLocale($locale);
|
|
CarbonPeriod::setLocale($locale);
|
|
CarbonInterval::setLocale($locale);
|
|
|
|
Carbon::setFallbackLocale($fallback);
|
|
CarbonImmutable::setFallbackLocale($fallback);
|
|
CarbonPeriod::setFallbackLocale($fallback);
|
|
CarbonInterval::setFallbackLocale($fallback);
|
|
|
|
IlluminateCarbon::setLocale($locale);
|
|
|
|
if (
|
|
method_exists(
|
|
IlluminateCarbon::class,
|
|
'setFallbackLocale'
|
|
)
|
|
) {
|
|
IlluminateCarbon::setFallbackLocale($fallback);
|
|
}
|
|
|
|
try {
|
|
$date = Date::getFacadeRoot();
|
|
|
|
if ($date && method_exists($date, 'setLocale')) {
|
|
$date->setLocale($locale);
|
|
}
|
|
|
|
if (
|
|
$date &&
|
|
method_exists($date, 'setFallbackLocale')
|
|
) {
|
|
$date->setFallbackLocale($fallback);
|
|
}
|
|
} catch (Throwable) {
|
|
// Preserve Carbon provider tolerance for custom Date drivers.
|
|
}
|
|
}
|
|
}
|