|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace mindtwo\LaravelMultilingual\Models\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Facades\Cache; |
|
6
|
|
|
|
|
7
|
|
|
trait TranslationCalls |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* Boot the translation calls trait for a model. |
|
11
|
|
|
*/ |
|
12
|
|
|
public static function bootTranslationCalls() |
|
13
|
|
|
{ |
|
14
|
|
|
static::updated(function (self $model) { |
|
15
|
|
|
$model->flushGroupCache(); |
|
16
|
|
|
}); |
|
17
|
|
|
|
|
18
|
|
|
static::deleted(function (self $model) { |
|
19
|
|
|
$model->flushGroupCache(); |
|
20
|
|
|
}); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Get translation based on a given group and key. |
|
25
|
|
|
* |
|
26
|
|
|
* @param string $locale |
|
27
|
|
|
* @param string $group |
|
28
|
|
|
* |
|
29
|
|
|
* @return array |
|
30
|
|
|
*/ |
|
31
|
|
|
public static function getTranslationsForGroup(string $locale, string $group): array |
|
32
|
|
|
{ |
|
33
|
|
|
return Cache::rememberForever(static::getCacheKey($group, $locale), function () use ($group, $locale) { |
|
34
|
|
|
return static::query() |
|
35
|
|
|
->where(function ($query) use ($group) { |
|
36
|
|
|
$query->where('group', $group); |
|
37
|
|
|
$query->orWhere('group', 'LIKE', $group.'.%'); |
|
38
|
|
|
}) |
|
39
|
|
|
->where('locale', $locale) |
|
40
|
|
|
->get() |
|
41
|
|
|
->reduce(function ($lines, $model) use ($group) { |
|
|
|
|
|
|
42
|
|
|
if (! is_null($model->value)) { |
|
43
|
|
|
$group = collect(explode('.', $model->group)) |
|
44
|
|
|
->slice(1) // Remove first entry for laravel compatibility. The first segment is the filename on the default file loader. |
|
45
|
|
|
->push($model->key) // Push translation key as a last segment |
|
46
|
|
|
->implode('.'); |
|
47
|
|
|
|
|
48
|
|
|
// Inverse of array_dot() function. |
|
49
|
|
|
array_set($lines, $group, $model->value); |
|
|
|
|
|
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
return $lines; |
|
53
|
|
|
}) ?? []; |
|
54
|
|
|
}); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* Generate cache key. |
|
59
|
|
|
* |
|
60
|
|
|
* @param string $group |
|
61
|
|
|
* @param string $locale |
|
62
|
|
|
* |
|
63
|
|
|
* @return string |
|
64
|
|
|
*/ |
|
65
|
|
|
public static function getCacheKey(string $group, string $locale): string |
|
66
|
|
|
{ |
|
67
|
|
|
$classNameArray = explode('\\', __CLASS__); |
|
68
|
|
|
$className = last($classNameArray); |
|
69
|
|
|
|
|
70
|
|
|
return strtolower("translations.{$className}.{$group}.{$locale}"); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* Flush translation cache. |
|
75
|
|
|
* |
|
76
|
|
|
* @return bool |
|
77
|
|
|
*/ |
|
78
|
|
|
protected function flushGroupCache() |
|
79
|
|
|
{ |
|
80
|
|
|
return Cache::forget(static::getCacheKey($this->group ?? '', $this->locale)); |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|
This check looks for imports that have been defined, but are not used in the scope.