Skip to content

Commit 15b63a8

Browse files
authored
Add Option to Disable Cache on LoadLocale (#22)
* Do not cache locales * wip Co-authored-by: Niken Sawitri <niken@suitmedia.com>
1 parent 27b178b commit 15b63a8

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

config/i18n.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,5 +97,15 @@
9797
| translation table name.
9898
|
9999
*/
100-
'translation_table_suffix' => 'translations'
100+
'translation_table_suffix' => 'translations',
101+
102+
/*
103+
|--------------------------------------------------------------------------
104+
| Enable Store to the cache
105+
|--------------------------------------------------------------------------
106+
|
107+
| Toggle store locale to the cache
108+
|
109+
*/
110+
'enable_cache' => env('I18N_ENABLE_CACHE', true),
101111
];

src/I18nService.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,10 @@ protected function loadLocale(): Collection
180180
$duration = $this->getConfig('cache_duration', 86400);
181181
$ttl = Carbon::now()->addSeconds($duration);
182182

183+
if (!$this->getConfig('enable_cache')) {
184+
return app(RepositoryManager::class)->collect();
185+
}
186+
183187
return \Cache::remember($cacheKey, $ttl, function () {
184188
return app(RepositoryManager::class)->collect();
185189
});

tests/I18nServiceTests.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,30 @@ public function it_can_load_locale_from_repository()
151151
$this->assertEquals(null, $collection->get('ch'));
152152
}
153153

154+
/** @test */
155+
public function it_caches_locale()
156+
{
157+
$cacheKey = 'laravel-i18n-locale-'.$this->service->getConfig('driver');
158+
\Cache::forget($cacheKey);
159+
$collection = $this->invokeMethod($this->service, 'loadLocale');
160+
161+
$this->assertEquals($collection->get('en'), \Cache::get($cacheKey)->get('en'));
162+
$this->assertEquals($collection->get('es'), \Cache::get($cacheKey)->get('es'));
163+
$this->assertEquals($collection->get('de'), \Cache::get($cacheKey)->get('de'));
164+
}
165+
166+
/** @test */
167+
public function it_does_not_cache_locale()
168+
{
169+
$this->app['config']->set('i18n.enable_cache', false);
170+
$this->invokeMethod($this->service, 'loadConfig');
171+
$cacheKey = 'laravel-i18n-locale-'.$this->service->getConfig('driver');
172+
\Cache::forget($cacheKey);
173+
$this->invokeMethod($this->service, 'loadLocale');
174+
175+
$this->assertEquals(null, \Cache::get($cacheKey));
176+
}
177+
154178
/** @test */
155179
public function it_can_determine_the_routed_locale_based_on_the_given_request_object()
156180
{

0 commit comments

Comments
 (0)