Skip to content

Commit f8d60b0

Browse files
authored
Merge pull request #14 from sl0wik/feature/translation_helper
Translation helper
2 parents b7a95d2 + d7b22a0 commit f8d60b0

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/Models/Translation.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
namespace Sl0wik\Webset\Models;
4+
5+
use Illuminate\Database\Eloquent\Model;
6+
use Illuminate\Support\Facades\Cache;
7+
8+
class Translation extends Model
9+
{
10+
/**
11+
* Get cached translations for current website.
12+
*
13+
* @return Illuminate\Database\Eloquent\Collection
14+
*/
15+
public static function getCached()
16+
{
17+
$class = self::class;
18+
$websiteId = env('WEBSITE_ID');
19+
$key = "{$class}.websiteId:{$websiteId}";
20+
if (Cache::has($key)) {
21+
$cached = Cache::get($key);
22+
} else {
23+
$cached = self::where($websiteId)->get();
24+
Cache::put($class, $cached, config('cache.translations.lifetime', 10));
25+
}
26+
27+
return $cached;
28+
}
29+
}

src/helpers.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,34 @@
11
<?php
22

3+
/**
4+
* Short function to return key from dictionary. Laravel trans() helper behing.
5+
*
6+
* @param string $key Key name like "dict.test".
7+
* @param string|null $data Optional parameters to trans.
8+
*
9+
* @return string
10+
*/
11+
function __t($key, $data = null)
12+
{
13+
if (\Lang::has($key)) {
14+
if ($data) {
15+
return trans($key, $data);
16+
} else {
17+
return trans($key);
18+
}
19+
} else {
20+
// TODO: we need parsing like in trans
21+
$translation = Sl0wik\Webset\Models\Translation::getCached();
22+
$item = $translation->where('language_code', \LaravelLocalization::getCurrentLocale())->where('key', $key)->first();
23+
24+
if ($item) {
25+
return $item->value;
26+
} else {
27+
return $key;
28+
}
29+
}
30+
}
31+
332
/**
433
* Returning translated (lozalized) url.
534
*

0 commit comments

Comments
 (0)