Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 1 | <?php |
| 2 | |
Matthias Andreas Benkard | 1ba5381 | 2022-12-27 17:32:58 +0100 | [diff] [blame^] | 3 | /** |
| 4 | * This file is part of the Carbon package. |
| 5 | * |
| 6 | * (c) Brian Nesbitt <brian@nesbot.com> |
| 7 | * |
| 8 | * For the full copyright and license information, please view the LICENSE |
| 9 | * file that was distributed with this source code. |
| 10 | */ |
| 11 | |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 12 | namespace Carbon\Laravel; |
| 13 | |
| 14 | use Carbon\Carbon; |
| 15 | use Carbon\CarbonImmutable; |
| 16 | use Carbon\CarbonInterval; |
| 17 | use Carbon\CarbonPeriod; |
| 18 | use Illuminate\Contracts\Events\Dispatcher as DispatcherContract; |
| 19 | use Illuminate\Events\Dispatcher; |
| 20 | use Illuminate\Events\EventDispatcher; |
| 21 | use Illuminate\Support\Carbon as IlluminateCarbon; |
| 22 | use Illuminate\Support\Facades\Date; |
| 23 | use Throwable; |
| 24 | |
| 25 | class ServiceProvider extends \Illuminate\Support\ServiceProvider |
| 26 | { |
| 27 | public function boot() |
| 28 | { |
| 29 | $this->updateLocale(); |
| 30 | |
| 31 | if (!$this->app->bound('events')) { |
| 32 | return; |
| 33 | } |
| 34 | |
| 35 | $service = $this; |
| 36 | $events = $this->app['events']; |
| 37 | |
| 38 | if ($this->isEventDispatcher($events)) { |
| 39 | $events->listen(class_exists('Illuminate\Foundation\Events\LocaleUpdated') ? 'Illuminate\Foundation\Events\LocaleUpdated' : 'locale.changed', function () use ($service) { |
| 40 | $service->updateLocale(); |
| 41 | }); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | public function updateLocale() |
| 46 | { |
| 47 | $app = $this->app && method_exists($this->app, 'getLocale') ? $this->app : app('translator'); |
| 48 | $locale = $app->getLocale(); |
| 49 | Carbon::setLocale($locale); |
| 50 | CarbonImmutable::setLocale($locale); |
| 51 | CarbonPeriod::setLocale($locale); |
| 52 | CarbonInterval::setLocale($locale); |
| 53 | |
| 54 | if (class_exists(IlluminateCarbon::class)) { |
| 55 | IlluminateCarbon::setLocale($locale); |
| 56 | } |
| 57 | |
| 58 | if (class_exists(Date::class)) { |
| 59 | try { |
| 60 | $root = Date::getFacadeRoot(); |
| 61 | $root->setLocale($locale); |
| 62 | } catch (Throwable $e) { |
| 63 | // Non Carbon class in use in Date facade |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | public function register() |
| 69 | { |
| 70 | // Needed for Laravel < 5.3 compatibility |
| 71 | } |
| 72 | |
| 73 | protected function isEventDispatcher($instance) |
| 74 | { |
| 75 | return $instance instanceof EventDispatcher |
| 76 | || $instance instanceof Dispatcher |
| 77 | || $instance instanceof DispatcherContract; |
| 78 | } |
| 79 | } |