diff --git a/src/Mcamara/LaravelLocalization/LaravelLocalization.php b/src/Mcamara/LaravelLocalization/LaravelLocalization.php index 1f9cbe8..ce0e400 100644 --- a/src/Mcamara/LaravelLocalization/LaravelLocalization.php +++ b/src/Mcamara/LaravelLocalization/LaravelLocalization.php @@ -138,12 +138,7 @@ public function __construct() $this->url = $this->app['url']; // set default locale - $this->defaultLocale = $this->configRepository->get('app.locale'); - $supportedLocales = $this->getSupportedLocales(); - - if (empty($supportedLocales[$this->defaultLocale])) { - throw new UnsupportedLocaleException('Laravel default locale is not in the supportedLocales array.'); - } + $this->setDefaultLocale($this->configRepository->get('app.locale')); } /** @@ -414,6 +409,22 @@ public function getDefaultLocale() return $this->defaultLocale; } + /** + * Sets the default locale. + * + * @param $defaultLocale + * @throws UnsupportedLocaleException + * @throws SupportedLocalesNotDefined + */ + public function setDefaultLocale($defaultLocale) + { + $supportedLocales = $this->getSupportedLocales(); + if (empty($supportedLocales[$defaultLocale])) { + throw new UnsupportedLocaleException('Laravel default locale is not in the supportedLocales array.'); + } + $this->defaultLocale = $defaultLocale; + } + /** * Return locales mapping. * diff --git a/tests/LocalizerTests.php b/tests/LocalizerTests.php index 80f83f6..30f1b69 100644 --- a/tests/LocalizerTests.php +++ b/tests/LocalizerTests.php @@ -880,4 +880,46 @@ public function testSetLocaleWithMapping() $this->assertEquals('http://localhost/custom/some-route', app('laravellocalization')->localizeURL('some-route', 'custom')); $this->assertEquals('http://localhost/custom', app('laravellocalization')->localizeURL('http://localhost/custom', 'en')); } + + public function testSetDefaultLocale() + { + $this->assertEquals( + app('laravellocalization')->getDefaultLocale(), $this->defaultLocale + ); + + app('laravellocalization')->setDefaultLocale('es'); + + $this->assertEquals( + app('laravellocalization')->getDefaultLocale(), 'es' + ); + } + + public function testSetInvalidDefaultLocale() + { + $this->expectException(\Mcamara\LaravelLocalization\Exceptions\UnsupportedLocaleException::class); + app('laravellocalization')->setDefaultLocale('sv'); + } + + public function testSetDefaultLocaleHiddenInUrl() + { + app('config')->set('laravellocalization.hideDefaultLocaleInURL', true); + + $this->assertEquals( + $this->test_url, + app('laravellocalization')->localizeURL('', $this->defaultLocale) + ); + + app('laravellocalization')->setDefaultLocale('es'); + + $this->assertNotEquals( + $this->test_url, + app('laravellocalization')->localizeURL('', $this->defaultLocale) + ); + + $this->assertEquals( + $this->test_url, + app('laravellocalization')->localizeURL('', 'es') + ); + + } }