blob: 8be0569e8f5632ccd2a06771c2ac96eb45711b2c [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +01003/**
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 Benkard7b2a3a12021-08-16 10:57:25 +020012namespace Carbon\Laravel;
13
14use Carbon\Carbon;
15use Carbon\CarbonImmutable;
16use Carbon\CarbonInterval;
17use Carbon\CarbonPeriod;
18use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
19use Illuminate\Events\Dispatcher;
20use Illuminate\Events\EventDispatcher;
21use Illuminate\Support\Carbon as IlluminateCarbon;
22use Illuminate\Support\Facades\Date;
23use Throwable;
24
25class 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}