@@ -23,12 +23,39 @@ class TextTemplate
2323 /** @var string */
2424 private $ closeChar = '} ' ;
2525
26+ /**
27+ * TextTemplate constructor.
28+ * @param array $vars
29+ */
30+ public function __construct (array $ vars = [])
31+ {
32+ if ($ vars ) {
33+ $ this ->setVars ($ vars );
34+ }
35+ }
36+
37+ /**
38+ * @param string $tplFile
39+ * @param array $vars
40+ * @param null|string $saveAs
41+ * @return string|bool
42+ */
43+ public function renderFile (string $ tplFile , array $ vars = [], $ saveAs = null )
44+ {
45+ if (!\is_file ($ tplFile )) {
46+ throw new \InvalidArgumentException ("Template file not exists. FILE: $ tplFile " );
47+ }
48+
49+ return $ this ->render (file_get_contents ($ tplFile ), $ vars , $ saveAs );
50+ }
51+
2652 /**
2753 * @param string $template
2854 * @param array $vars
55+ * @param null|string $saveAs
2956 * @return string
3057 */
31- public function render (string $ template , array $ vars = [])
58+ public function render (string $ template , array $ vars = [], $ saveAs = null )
3259 {
3360 if (!$ template || false === strpos ($ template , $ this ->openChar )) {
3461 return $ template ;
@@ -38,14 +65,47 @@ public function render(string $template, array $vars = [])
3865 $ vars = array_merge ($ this ->vars , $ vars );
3966 }
4067
41- $ pairs = [];
68+ $ pairs = $ map = [];
69+ $ this ->expandVars ($ vars , $ map );
4270
43- foreach ($ vars as $ name => $ value ) {
71+ foreach ($ map as $ name => $ value ) {
4472 $ key = $ this ->openChar . $ name . $ this ->closeChar ;
4573 $ pairs [$ key ] = $ value ;
4674 }
4775
48- return strtr ($ template , $ pairs );
76+ // replace vars to values.
77+ $ rendered = strtr ($ template , $ pairs );
78+
79+ if (!$ saveAs ) {
80+ return $ rendered ;
81+ }
82+
83+ $ dstDir = \dirname ($ saveAs );
84+
85+ if (!is_dir ($ dstDir ) && !mkdir ($ dstDir , 0775 , true ) && !is_dir ($ dstDir )) {
86+ throw new \RuntimeException (sprintf ('Directory "%s" was not created ' , $ dstDir ));
87+ }
88+
89+ return (bool )file_put_contents ($ saveAs , $ rendered );
90+ }
91+
92+ /**
93+ * Multidimensional array expansion to one dimension array
94+ * @param array $vars
95+ * @param null|string $prefix
96+ * @param array $map
97+ */
98+ protected function expandVars (array $ vars , array &$ map = [], $ prefix = null )
99+ {
100+ foreach ($ vars as $ name => $ value ) {
101+ $ key = $ prefix !== null ? $ prefix . '. ' . $ name : $ name ;
102+
103+ if (is_scalar ($ value )) {
104+ $ map [$ key ] = $ value ;
105+ } elseif (\is_array ($ value )) {
106+ $ this ->expandVars ($ value , $ map , (string )$ key );
107+ }
108+ }
49109 }
50110
51111 /**
0 commit comments