22
33namespace Major \Fluent \Laravel ;
44
5+ use Closure ;
56use Countable ;
67use Illuminate \Contracts \Translation \Loader ;
78use Illuminate \Contracts \Translation \Translator as TranslatorContract ;
89use Illuminate \Filesystem \Filesystem ;
910use Illuminate \Translation \MessageSelector ;
1011use Illuminate \Translation \Translator as BaseTranslator ;
1112use Major \Fluent \Bundle \FluentBundle ;
13+ use Major \Fluent \Exceptions \Bundle \FunctionExistsException ;
1214
1315final class FluentTranslator implements TranslatorContract
1416{
1517 /** @var array<string, array<string, FluentBundle|false>> */
1618 private array $ loaded = [];
1719
20+ /** @var array<string, Closure> */
21+ private array $ functions = [];
22+
1823 public function __construct (
1924 protected BaseTranslator $ baseTranslator ,
2025 protected Filesystem $ files ,
@@ -62,6 +67,23 @@ public function get($key, array $replace = [], $locale = null, bool $fallback =
6267 return $ message ?? $ this ->baseTranslator ->get (...func_get_args ());
6368 }
6469
70+ public function addFunction (string $ name , Closure $ function ): void
71+ {
72+ if (array_key_exists ($ name , $ this ->functions )) {
73+ throw new FunctionExistsException ($ name );
74+ }
75+
76+ $ this ->functions [$ name ] = $ function ;
77+
78+ foreach ($ this ->loaded as $ locale ) {
79+ foreach ($ locale as $ bundle ) {
80+ if ($ bundle !== false ) {
81+ $ bundle ->addFunction ($ name , $ function );
82+ }
83+ }
84+ }
85+ }
86+
6587 private function getBundle (string $ locale , string $ group ): ?FluentBundle
6688 {
6789 if (! isset ($ this ->loaded [$ locale ][$ group ])) {
@@ -80,7 +102,8 @@ private function loadFtl(string $locale, string $group): ?FluentBundle
80102 }
81103
82104 return (new FluentBundle ($ locale , ...$ this ->bundleOptions ))
83- ->addFtl ($ this ->files ->get ($ path ));
105+ ->addFtl ($ this ->files ->get ($ path ))
106+ ->addFunctions ($ this ->functions );
84107 }
85108
86109 /**
0 commit comments