Created
October 30, 2014 11:00
-
-
Save achtan/4948273a68146825a9cf to your computer and use it in GitHub Desktop.
Translateble
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Dictionary; | |
use Nette\Localization\ITranslator; | |
class Translatable | |
{ | |
const TYPE_STRING = 'string'; | |
const TYPE_PHRASE = 'phrase'; | |
/** | |
* @var array | |
*/ | |
protected $sentence = []; | |
/** | |
* @param $string | |
* | |
* @return Translatable | |
*/ | |
public function string($string) | |
{ | |
return $this->add(self::TYPE_STRING, $string); | |
} | |
/** | |
* @param $phrase | |
* | |
* @return Translatable | |
*/ | |
public function phrase($phrase) | |
{ | |
return $this->add(self::TYPE_PHRASE, $phrase); | |
} | |
/** | |
* @param $type | |
* @param $value | |
* | |
* @return Translatable | |
*/ | |
public function add($type, $value) | |
{ | |
$this->sentence[] = [ | |
'type' => $type, | |
'value' => $value, | |
]; | |
return $this; | |
} | |
/** | |
* @param ITranslator $translator | |
* | |
* @return string | |
*/ | |
public function translate(ITranslator $translator) | |
{ | |
$string = ''; | |
foreach($this->sentence as $key => $value) { | |
if($value['type'] == self::TYPE_PHRASE) { | |
$value['value'] = call_user_func_array([$translator, 'translate'], $value['value']); | |
} | |
$string .= $value['value']; | |
} | |
return $string; | |
} | |
/** | |
* @return Translatable | |
*/ | |
public static function from() | |
{ | |
$t = new self; | |
$args = func_get_args(); | |
foreach($args as $arg) { | |
if(is_scalar($arg)) { | |
$t->string($arg); | |
} else if(is_array($arg)) { | |
$t->phrase($arg); | |
} | |
} | |
return $t; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment