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