Skip to content

Commit

Permalink
Add validation for translated strings
Browse files Browse the repository at this point in the history
  • Loading branch information
mjauvin authored Mar 18, 2024
1 parent 78710da commit aecd17c
Showing 1 changed file with 29 additions and 12 deletions.
41 changes: 29 additions & 12 deletions classes/TranslatableBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,26 @@ public function __construct($model)
}
});

$this->model->bindEvent('model.saveInternal', function() {
$this->model->bindEvent('model.getValidationAttributes', function ($attributes) {
if (($locale = $this->translateContext()) !== $this->translatableDefault) {
foreach ($this->getTranslateDirty($locale) as $key => $value) {
if (!empty($value)) {
$attributes[$key] = $value;
}
}
return $attributes;
}
}, 1000);

$this->model->bindEvent('model.saveInternal', function () {
$this->syncTranslatableAttributes();

if (method_exists($this->model, 'validate')) {
foreach ($this->getDirtyLocales() as $locale) {
$this->translateContext($locale);
$this->model->validate();
}
}
});
}

Expand Down Expand Up @@ -316,25 +334,24 @@ public function syncTranslatableAttributes()
}

/**
* Changes the active language for this model
* @param string $context
* @return void
* Change the active language for this model
* @param string|null $context
* @return string
*/
public function translateContext($context = null)
public function translateContext($context = null): string
{
if ($context === null) {
return $this->translatableContext;
if ($context) {
$this->translatableContext = $context;
}

$this->translatableContext = $context;
return $this->translatableContext;
}

/**
* Shorthand for translateContext method, and chainable.
* @param string $context
* Chainable shorthand for translateContext method
* @param string|null $context
* @return self
*/
public function lang($context = null)
public function lang($context = null): self
{
$this->translateContext($context);

Expand Down

0 comments on commit aecd17c

Please sign in to comment.