manual merge of fixes for CRM-13981
[civicrm-core.git] / CRM / Core / CodeGen / Util / Template.php
1 <?php
2
3 class CRM_Core_CodeGen_Util_Template {
4 protected $filetype;
5
6 protected $smarty;
7 protected $beautifier;
8
9 // FIXME: Set by Main...
10 static public $smartyPluginDirs = array();
11
12 /**
13 * @param string $filetype
14 */
15 function __construct($filetype) {
16 $this->compileDir = CRM_Core_CodeGen_Util_File::createTempDir('templates_c_');
17
18 // TODO use Core Smarty
19 require_once 'Smarty/Smarty.class.php';
20 $this->smarty = new Smarty();
21 $this->smarty->template_dir = './templates';
22 $this->smarty->plugins_dir = self::$smartyPluginDirs;
23 $this->smarty->compile_dir = $this->compileDir;
24 $this->smarty->clear_all_cache();
25
26 $this->assign('generated', "DO NOT EDIT. Generated by CRM_Core_CodeGen");
27
28 // CRM-5308 / CRM-3507 - we need {localize} to work in the templates
29 require_once 'CRM/Core/Smarty/plugins/block.localize.php';
30 $this->smarty->register_block('localize', 'smarty_block_localize');
31
32 if ($this->filetype === 'php') {
33 require_once 'PHP/Beautifier.php';
34 // create an instance
35 $this->beautifier = new PHP_Beautifier();
36 $this->beautifier->addFilter('ArrayNested');
37 // add one or more filters
38 $this->beautifier->addFilter('Pear');
39 // add one or more filters
40 $this->beautifier->addFilter('NewLines', array('after' => 'class, public, require, comment'));
41 $this->beautifier->setIndentChar(' ');
42 $this->beautifier->setIndentNumber(2);
43 $this->beautifier->setNewLine("\n");
44 }
45 }
46
47 function __destruct() {
48 CRM_Core_CodeGen_Util_File::removeDir($this->compileDir);
49 }
50
51 /**
52 * @param array $inputs template filenames
53 * @param string $outpath full path to the desired output file
54 */
55 function runConcat($inputs, $outpath) {
56 if (file_exists($outpath)) {
57 unlink($outpath);
58 }
59 foreach ($inputs as $infile) {
60 // FIXME: does not beautify. Document.
61 file_put_contents($outpath, $this->smarty->fetch($infile) ."\n", FILE_APPEND);
62 }
63 }
64
65 /**
66 * @param string $infile filename of the template, without a path
67 * @param string $outpath full path to the desired output file
68 */
69 function run($infile, $outpath) {
70 $renderedContents = $this->smarty->fetch($infile);
71
72 if ($this->filetype === 'php') {
73 $this->beautifier->setInputString($renderedContents);
74 $this->beautifier->setOutputFile($outpath);
75 $this->beautifier->process();
76 $this->beautifier->save();
77 } else {
78 file_put_contents($outpath, $renderedContents);
79 }
80 }
81
82 function assign($key, $value) {
83 $this->smarty->assign_by_ref($key, $value);
84 }
85
86 /**
87 * Clear the smarty cache and assign default values
88 * FIXME: unused cos we no longer do evil singleton magick
89 */
90 protected function reset() {
91 $this->smarty->clear_all_assign();
92 $this->smarty->clear_all_cache();
93 }
94 }