namespace Cubist\Backpack\Magic\Models;
use Cubist\Backpack\Facades\App;
+use Cubist\Backpack\Magic\Fields\FormSection;
use Cubist\Backpack\Magic\Fields\Hidden;
+use Cubist\Backpack\Magic\Fields\Textarea;
class Translate extends CubistMagicTranslatableModel
{
$seenStrings = [];
+ $currentSection = '-';
+ $sections = [$currentSection => []];
+
foreach ($translate->getStringToTranslate() as $sectionLabel => $strings) {
$toTranslate = [];
foreach ($strings as $string) {
continue;
}
if (!is_numeric($sectionLabel)) {
- $this->addField($sectionLabel, 'FormSection', $sectionLabel);
+ if (!$sectionLabel || $sectionLabel=='0') {
+ $sectionLabel = '-';
+ }
+ $currentSection = $sectionLabel;
+ if (!isset($sections[$currentSection])) {
+ $sections[$currentSection] = [];
+ }
}
foreach ($toTranslate as $string) {
- $key = 't_' . base64_encode($string);
+ if (str_starts_with($string, '!!')) {
+ $currentSection = ltrim($string, '!');
+ if (!isset($sections[$currentSection])) {
+ $sections[$currentSection] = [];
+ }
+ continue;
+ }
+ $key = self::_encodeKey($string);
- if(is_string($string)){
- $label=e($string);
- }else{
- $label='??';
+ if (is_string($string)) {
+ $label = e($string);
+ } else {
+ $label = '??';
}
- $this->addField(['name' => $key,
+ $sections[$currentSection][] = ['name' => $key,
'label' => $label,
- 'type' => 'Textarea',
+ 'type' => Textarea::class,
+ 'rows' => 1,
'translatable' => true,
'store_in' => 'content',
- 'fake' => true]);
+ 'fake' => true];
+ }
+ }
+
+ foreach ($sections as $section => $fields) {
+ if (!count($fields)) {
+ continue;
+ }
+ $this->addField($section, FormSection::class, $section);
+ foreach ($fields as $field) {
+ if(!$field){
+ continue;
+ }
+ $this->addField($field);
}
}
}
+ protected static function _encodeKey($string)
+ {
+ return 't_' . base64_encode($string);
+ }
+
- public function onSaving():bool
+ public function onSaving(): bool
{
$this->saveLanguageFile();
+
+ $default = $this->_defaultTranslations();
+
+ $all = $this->attributes;
+
+ $content = json_decode($all['content_translatable'], true);
+ foreach ($default as $locale => $translations) {
+ foreach ($translations as $str => $translation) {
+ if (!$translation) {
+ continue;
+ }
+ $key = self::_encodeKey($str);
+ if (!isset($content[$locale][$key]) || !$content[$locale][$key]) {
+ $content[$locale][$key] = $translation;
+ }
+ }
+ }
+
+ $all['content_translatable'] = json_encode($content);
+ $this->setRawAttributes($all);
+
return parent::onSaving();
}
- public function onSaved():bool
+ public function onSaved(): bool
{
$this->saveLanguageFile();
return parent::onSaved();
{
return 1;
}
+
+ /**
+ * @return array[]
+ */
+ protected function _defaultTranslations()
+ {
+ return [];
+ }
}