blob: d71c888b294a89d5e353e2e61982eb515c819823 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3namespace Carbon\Laravel;
4
5use Carbon\Carbon;
6use Carbon\CarbonImmutable;
7use Carbon\CarbonInterval;
8use Carbon\CarbonPeriod;
9use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
10use Illuminate\Events\Dispatcher;
11use Illuminate\Events\EventDispatcher;
12use Illuminate\Support\Carbon as IlluminateCarbon;
13use Illuminate\Support\Facades\Date;
14use Throwable;
15
16class 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}