1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace KoenHoeijmakers\LaravelTranslatable\Services; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
|
7
|
|
|
class TranslationSavingService |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* The translations that are being stored in this request. |
11
|
|
|
* |
12
|
|
|
* @var array |
13
|
|
|
*/ |
14
|
|
|
protected $translations = []; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Remember the translation for the given model. |
18
|
|
|
* |
19
|
|
|
* @param \Illuminate\Database\Eloquent\Model|\KoenHoeijmakers\LaravelTranslatable\HasTranslations $model |
20
|
|
|
* @return void |
21
|
|
|
*/ |
22
|
24 |
|
public function rememberTranslationForModel(Model $model) |
23
|
|
|
{ |
24
|
24 |
|
$attributes = $model->getTranslatableAttributes(); |
25
|
|
|
|
26
|
24 |
|
$this->rememberTranslation($this->getModelIdentifier($model), $attributes); |
|
|
|
|
27
|
|
|
|
28
|
24 |
|
foreach (array_keys($attributes) as $attribute) { |
|
|
|
|
29
|
24 |
|
$model->offsetUnset($attribute); |
30
|
|
|
} |
31
|
24 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Store the remembered translation for the given model. |
35
|
|
|
* |
36
|
|
|
* @param \Illuminate\Database\Eloquent\Model|\KoenHoeijmakers\LaravelTranslatable\HasTranslations $model |
37
|
|
|
* @return void |
38
|
|
|
*/ |
39
|
24 |
|
public function storeTranslationOnModel(Model $model) |
40
|
|
|
{ |
41
|
24 |
|
$identifier = $this->getModelIdentifier($model); |
42
|
|
|
|
43
|
24 |
|
$model->storeTranslation( |
44
|
24 |
|
$model->getLocale(), |
45
|
24 |
|
$this->pullRememberedTranslation($identifier) |
46
|
|
|
); |
47
|
24 |
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Remember the translation on the given key. |
51
|
|
|
* |
52
|
|
|
* @param string $key |
53
|
|
|
* @param array $attributes |
54
|
|
|
* @return void |
55
|
|
|
*/ |
56
|
24 |
|
public function rememberTranslation(string $key, array $attributes) |
57
|
|
|
{ |
58
|
24 |
|
$this->translations[$key] = $attributes; |
59
|
24 |
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Pull the translation on the given key. |
63
|
|
|
* |
64
|
|
|
* @param string $key |
65
|
|
|
* @return mixed |
66
|
|
|
*/ |
67
|
24 |
|
public function pullRememberedTranslation(string $key) |
68
|
|
|
{ |
69
|
24 |
|
$value = $this->translations[$key]; |
70
|
|
|
|
71
|
24 |
|
unset($this->translations[$key]); |
72
|
|
|
|
73
|
24 |
|
return $value; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* Get an unique identifier for the given model. |
78
|
|
|
* |
79
|
|
|
* @param \Illuminate\Database\Eloquent\Model $model |
80
|
|
|
* @return string |
81
|
|
|
*/ |
82
|
24 |
|
protected function getModelIdentifier(Model $model): string |
83
|
|
|
{ |
84
|
24 |
|
return spl_object_hash($model); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|