Skip to content

Commit

Permalink
Add Translator::translateOrNull() method
Browse files Browse the repository at this point in the history
  • Loading branch information
BenMorel committed Jul 9, 2018
1 parent a44432e commit 57d95a2
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,34 @@ public function translate(string $key, array $params = [], string $locale = null
return $text;
}

/**
* @param string $key The translation key.
* @param array $params The named parameters to replace in the translated text. Optional.
* @param string|null $locale The locale to translate to. Optional if a default locale has been set.
*
* @return string|null The translated string, or null if not available.
*
* @throws \RuntimeException If no locale is provided, and no default locale has been set.
*/
public function translateOrNull(string $key, array $params = [], string $locale = null) : ?string
{
if ($locale === null) {
if ($this->defaultLocale === null) {
throw new \RuntimeException('No default locale has been set. A locale must be provided.');
}

$locale = $this->defaultLocale;
}

$text = $this->rawTranslate($key, $locale);

if ($text !== null && $params) {
$text = $this->replaceParameters($text, $params);
}

return $text;
}

/**
* Replaces parameters in a string.
*
Expand Down

0 comments on commit 57d95a2

Please sign in to comment.