Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame^] | 1 | <?php |
| 2 | |
| 3 | namespace Carbon\Laravel; |
| 4 | |
| 5 | use Carbon\Carbon; |
| 6 | use Carbon\CarbonImmutable; |
| 7 | use Carbon\CarbonInterval; |
| 8 | use Carbon\CarbonPeriod; |
| 9 | use Illuminate\Contracts\Events\Dispatcher as DispatcherContract; |
| 10 | use Illuminate\Events\Dispatcher; |
| 11 | use Illuminate\Events\EventDispatcher; |
| 12 | use Illuminate\Support\Carbon as IlluminateCarbon; |
| 13 | use Illuminate\Support\Facades\Date; |
| 14 | use Throwable; |
| 15 | |
| 16 | class ServiceProvider extends \Illuminate\Support\ServiceProvider |
| 17 | { |
| 18 | public function boot() |
| 19 | { |
| 20 | $this->updateLocale(); |
| 21 | |
| 22 | if (!$this->app->bound('events')) { |
| 23 | return; |
| 24 | } |
| 25 | |
| 26 | $service = $this; |
| 27 | $events = $this->app['events']; |
| 28 | |
| 29 | if ($this->isEventDispatcher($events)) { |
| 30 | $events->listen(class_exists('Illuminate\Foundation\Events\LocaleUpdated') ? 'Illuminate\Foundation\Events\LocaleUpdated' : 'locale.changed', function () use ($service) { |
| 31 | $service->updateLocale(); |
| 32 | }); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | public function updateLocale() |
| 37 | { |
| 38 | $app = $this->app && method_exists($this->app, 'getLocale') ? $this->app : app('translator'); |
| 39 | $locale = $app->getLocale(); |
| 40 | Carbon::setLocale($locale); |
| 41 | CarbonImmutable::setLocale($locale); |
| 42 | CarbonPeriod::setLocale($locale); |
| 43 | CarbonInterval::setLocale($locale); |
| 44 | |
| 45 | if (class_exists(IlluminateCarbon::class)) { |
| 46 | IlluminateCarbon::setLocale($locale); |
| 47 | } |
| 48 | |
| 49 | if (class_exists(Date::class)) { |
| 50 | try { |
| 51 | $root = Date::getFacadeRoot(); |
| 52 | $root->setLocale($locale); |
| 53 | } catch (Throwable $e) { |
| 54 | // Non Carbon class in use in Date facade |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | public function register() |
| 60 | { |
| 61 | // Needed for Laravel < 5.3 compatibility |
| 62 | } |
| 63 | |
| 64 | protected function isEventDispatcher($instance) |
| 65 | { |
| 66 | return $instance instanceof EventDispatcher |
| 67 | || $instance instanceof Dispatcher |
| 68 | || $instance instanceof DispatcherContract; |
| 69 | } |
| 70 | } |