1: <?php
2:
3: namespace Charcoal\View\Mustache;
4:
5: use Closure;
6: use InvalidArgumentException;
7:
8:
9: use Mustache_LambdaHelper as LambdaHelper;
10:
11:
12: use Charcoal\Translator\Translator;
13:
14:
15: use Charcoal\View\Mustache\HelpersInterface;
16:
17: 18: 19:
20: class TranslatorHelpers implements HelpersInterface
21: {
22: 23: 24: 25: 26:
27: private $translator;
28:
29: 30: 31: 32: 33: 34: 35:
36: private $number;
37:
38: 39: 40: 41: 42:
43: private $locale;
44:
45: 46: 47: 48: 49:
50: private $domain;
51:
52: 53: 54:
55: public function __construct(array $data = null)
56: {
57: if (isset($data['translator']) && $data['translator'] instanceof Translator) {
58: $this->translator = $data['translator'];
59: }
60: }
61:
62: 63: 64: 65: 66: 67:
68: public function toArray()
69: {
70: return [
71: '_t' => $this
72: ];
73: }
74:
75: 76: 77: 78: 79:
80: protected function reset()
81: {
82: $this->number = null;
83: $this->domain = null;
84: $this->locale = null;
85: }
86:
87:
88:
89:
90:
91:
92: 93: 94: 95: 96: 97: 98:
99: public function __invoke($text, LambdaHelper $helper = null)
100: {
101: if (!$helper) {
102: $this->number = $text;
103: return $this;
104: }
105:
106: if ($this->translator) {
107: if ($this->number === null) {
108: $text = $this->translator->trans($text, [], $this->domain, $this->locale);
109: } else {
110: if (!is_numeric($this->number) && is_string($this->number)) {
111: $this->number = $helper->render('{{ '.$this->number.' }}');
112: }
113:
114: $text = $this->translator->transChoice($text, (int)$this->number, [], $this->domain, $this->locale);
115: }
116:
117: $this->reset();
118: }
119:
120:
121: return $helper->render($text);
122: }
123:
124: 125: 126: 127: 128: 129: 130: 131:
132: public function __isset($macro)
133: {
134: return boolval($macro);
135: }
136:
137: 138: 139: 140: 141: 142: 143: 144:
145: public function __get($macro)
146: {
147: if (!$this->translator) {
148: return $this;
149: }
150:
151: if ($macro === '_t' || $macro === '_n') {
152: return $this;
153: }
154:
155: if (in_array($macro, $this->translator->availableLocales())) {
156: $this->locale = $macro;
157: } elseif (in_array($macro, $this->translator->availableDomains())) {
158: $this->domain = $macro;
159: } else {
160: $this->number = $macro;
161: }
162:
163: return $this;
164: }
165: }
166: