Skip to content

Commit

Permalink
- removed check for Nette\Utils\Html (this is nette specific, so move…
Browse files Browse the repository at this point in the history
…d to nette-extension)

- added normalizeCallback - so other frameworks can set their specific normalize method
  • Loading branch information
Radovan Kepák committed Jun 3, 2019
1 parent cab4240 commit a19a343
Showing 1 changed file with 27 additions and 12 deletions.
39 changes: 27 additions & 12 deletions src/Translator.php
Expand Up @@ -25,6 +25,7 @@
* Class Translator
*
* @package Bckp\Translator
* @method string normalizeCallback(string $string)
*/
class Translator implements ITranslator {
/**
Expand All @@ -37,6 +38,11 @@ class Translator implements ITranslator {
*/
private $diagnostics;

/**
* @var callable
*/
private $normalizeCallback;

/**
* Translator constructor.
*
Expand All @@ -45,19 +51,27 @@ class Translator implements ITranslator {
*/
public function __construct(ICatalogue $catalogue, IDiagnostics $diagnostics = null) {
$this->catalogue = $catalogue;
$this->normalizeCallback = [$this, 'normalize'];
if ($this->diagnostics = $diagnostics) {
$this->diagnostics->setLocale($catalogue->locale());
}
}

/**
* @param callable $callback
*/
public function setNormalizeCallback(callable $callback) {
$this->normalizeCallback = $callback;
}

/**
* @param mixed $message
* @param mixed ...$parameters
* @return string
*/
public function translate($message, ...$parameters): string {
// html and empty are returned without processing
if (empty($message) || $message instanceof \Nette\Utils\Html)
if (empty($message))
return (string) $message;

// expand parameters
Expand Down Expand Up @@ -90,7 +104,8 @@ public function translate($message, ...$parameters): string {
}

if ($parameters) {
$result = @vsprintf($this->normalize($result), $parameters); // Intentionally @ as argument count can mismatch
$result = ($this->normalizeCallback)($result);
$result = @vsprintf($result, $parameters); // Intentionally @ as argument count can mismatch
}
} else {
$this->untranslated((string) $message);
Expand Down Expand Up @@ -134,21 +149,21 @@ protected function warn(string $message, ...$parameters): string {
return $message;
}

/**
* Normalize string to preserve nette placeholders
*
* @param string $string
* @return string
*/
protected function normalize(string $string): string {
return (string) str_replace(['%label', '%value', '%name'], ['%%label', '%%value', '%%name'], $string);
}

/**
* @param string $message
*/
protected function untranslated(string $message): void {
if ($this->diagnostics !== null)
$this->diagnostics->untranslated($message);
}

/**
* Normalize string to preserve frameworks placeholders
*
* @param string $string
* @return string
*/
public function normalize(string $string): string {
return (string) str_replace(['%label', '%value', '%name'], ['%%label', '%%value', '%%name'], $string);
}
}

0 comments on commit a19a343

Please sign in to comment.