- Attempt to make the first compilation non-blocking at all
[haanga.git] / lib / Haanga.php
blobd40532f5a4b0aaf4657d077a60787c12fba6cc21
1 <?php
2 /*
3 +---------------------------------------------------------------------------------+
4 | Copyright (c) 2010 César Rodas and Menéame Comunicacions S.L. |
5 +---------------------------------------------------------------------------------+
6 | Redistribution and use in source and binary forms, with or without |
7 | modification, are permitted provided that the following conditions are met: |
8 | 1. Redistributions of source code must retain the above copyright |
9 | notice, this list of conditions and the following disclaimer. |
10 | |
11 | 2. Redistributions in binary form must reproduce the above copyright |
12 | notice, this list of conditions and the following disclaimer in the |
13 | documentation and/or other materials provided with the distribution. |
14 | |
15 | 3. All advertising materials mentioning features or use of this software |
16 | must display the following acknowledgement: |
17 | This product includes software developed by César D. Rodas. |
18 | |
19 | 4. Neither the name of the César D. Rodas nor the |
20 | names of its contributors may be used to endorse or promote products |
21 | derived from this software without specific prior written permission. |
22 | |
23 | THIS SOFTWARE IS PROVIDED BY CÉSAR D. RODAS ''AS IS'' AND ANY |
24 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
25 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
26 | DISCLAIMED. IN NO EVENT SHALL CÉSAR D. RODAS BE LIABLE FOR ANY |
27 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
28 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
29 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND |
30 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
31 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
32 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE |
33 +---------------------------------------------------------------------------------+
34 | Authors: César Rodas <crodas@php.net> |
35 +---------------------------------------------------------------------------------+
38 define('HAANGA_VERSION', '1.1.3');
41 /**
42 * Haanga Runtime class
44 * Simple class to call templates efficiently. This class aims
45 * to reduce the compilation of a template as less a possible. Also
46 * it will not load in memory the compiler, except when there is not
47 * cache (compiled template) or it is out-dated.
50 class Haanga
52 protected static $cache_dir;
53 protected static $templates_dir='.';
54 protected static $debug;
55 protected static $bootstrap = NULL;
56 protected static $check_ttl;
57 protected static $check_get;
58 protected static $check_set;
59 protected static $use_autoload = TRUE;
60 protected static $hash_filename = TRUE;
61 protected static $compiler = array();
63 public static $has_compiled;
65 private function __construct()
67 /* The class can't be instanced */
70 final public static function AutoLoad($class)
72 static $loaded = array();
73 static $path;
75 if (!isset($loaded[$class]) && substr($class, 0, 6) === 'Haanga' && !class_exists($class, false)) {
76 if ($path === NULL) {
77 $path = dirname(__FILE__);
79 $file = $path.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $class).'.php';
80 if (is_file($file)) {
81 require $file;
83 $loaded[$class] = TRUE;
84 return;
87 return FALSE;
90 // configure(Array $opts) {{{
91 /**
92 * Configuration to load Haanga
94 * Options:
96 * - (string) cache_dir
97 * - (string) tempalte_dir
98 * - (callback) on_compile
99 * - (boolean) debug
100 * - (int) check_ttl
101 * - (callback) check_get
102 * - (callback) check_set
103 * - (boolean) autoload
104 * - (boolean) use_hash_filename
106 * @return void
108 final public static function configure(Array $opts)
110 foreach ($opts as $option => $value) {
111 switch (strtolower($option)) {
112 case 'cache_dir':
113 self::$cache_dir = $value;
114 break;
115 case 'template_dir':
116 self::$templates_dir = $value;
117 break;
118 case 'bootstrap':
119 if (is_callable($value)) {
120 self::$bootstrap = $value;
122 break;
123 case 'debug':
124 self::enableDebug((bool)$value);
125 break;
126 case 'check_ttl':
127 self::$check_ttl = (int)$value;
128 break;
129 case 'check_get':
130 if (is_callable($value)) {
131 self::$check_get = $value;
133 break;
134 case 'check_set':
135 if (is_callable($value)) {
136 self::$check_set = $value;
138 break;
139 case 'autoload':
140 self::$use_autoload = (bool)$value;
141 break;
142 case 'use_hash_filename':
143 self::$hash_filename = (bool)$value;
144 break;
145 case 'compiler':
146 if (is_array($value)) {
147 self::$compiler = $value;
149 break;
150 default:
151 continue;
155 // }}}
157 // checkCacheDir(string $dir) {{{
159 * Check the directory where the compiled templates
160 * are stored.
162 * @param string $dir
164 * @return void
166 public static function checkCacheDir()
168 $dir = self::$cache_dir;
169 if (!is_dir($dir)) {
170 $old = umask(0);
171 if (!mkdir($dir, 0777, TRUE)) {
172 throw new Haanga_Exception("{$dir} is not a valid directory");
174 umask($old);
176 if (!is_writable($dir)) {
177 throw new Haanga_Exception("{$dir} can't be written");
180 // }}}
182 // enableDebug($bool) {{{
183 public static function enableDebug($bool)
185 self::$debug = $bool;
187 // }}}
189 // safe_load(string $file, array $vars, bool $return, array $blocks) {{{
190 public static function Safe_Load($file, $vars = array(), $return=FALSE, $blocks=array())
192 try {
193 return self::Load($file, $vars, $return, $blocks);
194 } Catch (Exception $e) {
195 return "";
198 // }}}
200 // load(string $file, array $vars, bool $return, array $blocks) {{{
202 * Load
204 * Load template. If the template is already compiled, just the compiled
205 * PHP file will be included an used. If the template is new, or it
206 * had changed, the Haanga compiler is loaded in memory, and the template
207 * is compiled.
210 * @param string $file
211 * @param array $vars
212 * @param bool $return
213 * @param array $blocks
215 * @return string|NULL
217 public static function Load($file, $vars = array(), $return=FALSE, $blocks=array())
219 static $compiler;
220 if (empty(self::$cache_dir)) {
221 throw new Haanga_Exception("Cache dir or template dir is missing");
224 self::$has_compiled = FALSE;
226 $tpl = self::$templates_dir.'/'.$file;
227 $fnc = sha1($tpl);
228 $callback = "haanga_".$fnc;
230 if (is_callable($callback)) {
231 return $callback($vars, $return, $blocks);
234 $php = self::$hash_filename ? $fnc : $file;
235 $php = self::$cache_dir.'/'.$php.'.php';
237 $check = TRUE;
239 if (self::$check_ttl && self::$check_get && self::$check_set) {
240 /* */
241 if (call_user_func(self::$check_get, $callback)) {
242 /* disable checking for the next $check_ttl seconds */
243 $check = FALSE;
244 } else {
245 $result = call_user_func(self::$check_set, $callback, TRUE, self::$check_ttl);
249 if (TRUE||!is_file($php) || ($check && filemtime($tpl) > filemtime($php))) {
251 if (!is_file($tpl)) {
252 /* There is no template nor compiled file */
253 throw new Exception("View {$file} doesn't exists");
256 /* recompile */
257 if (!$compiler) {
258 self::checkCacheDir();
260 /* Load needed files (to avoid autoload as much as possible) */
261 $dir = dirname(__FILE__);
262 require_once "{$dir}/Haanga/AST.php";
263 require_once "{$dir}/Haanga/Compiler.php";
264 require_once "{$dir}/Haanga/Compiler/Runtime.php";
265 require_once "{$dir}/Haanga/Compiler/Parser.php";
266 require_once "{$dir}/Haanga/Compiler/Lexer.php";
267 require_once "{$dir}/Haanga/Generator/PHP.php";
268 require_once "{$dir}/Haanga/Extension.php";
269 require_once "{$dir}/Haanga/Extension/Filter.php";
270 require_once "{$dir}/Haanga/Extension/Tag.php";
272 /* load compiler (done just once) */
273 if (self::$use_autoload) {
274 spl_autoload_register(array(__CLASS__, 'AutoLoad'));
277 $compiler = new Haanga_Compiler_Runtime;
279 if (self::$bootstrap) {
280 /* call bootstrap hook, just the first time */
281 call_user_func(self::$bootstrap);
284 if (count(self::$compiler) != 0) {
285 foreach (self::$compiler as $opt => $value) {
286 Haanga_Compiler::setOption($opt, $value);
291 $compiler->reset();
293 if (self::$debug) {
294 $compiler->setDebug($php.".dump");
297 if (!is_dir(dirname($php))) {
298 $old = umask(0);
299 mkdir(dirname($php), 0777, TRUE);
300 umask($old);
303 $fp = fopen($php, "a+");
304 /* try to block PHP file */
305 if (!flock($fp, LOCK_EX | LOCK_NB)) {
306 /* couldn't block, another process is already compiling */
307 fclose($fp);
308 unset($fp);
311 $code = $compiler->compile_file($tpl, FALSE, $vars);
313 if (isset($fp)) {
314 ftruncate($fp, 0); // truncate file
315 fwrite($fp, "<?php".$code);
316 flock($fp, LOCK_UN); // release the lock
317 fclose($fp);
318 } else {
319 /* local eval */
320 eval($code);
322 self::$has_compiled = TRUE;
325 if (!is_callable($callback)) {
326 require $php;
329 if (!isset($HAANGA_VERSION) || $HAANGA_VERSION != HAANGA_VERSION) {
330 touch($php, 300, 300);
331 chmod($php, 0777);
334 return $callback($vars, $return, $blocks);
336 // }}}
341 * Local variables:
342 * tab-width: 4
343 * c-basic-offset: 4
344 * End:
345 * vim600: sw=4 ts=4 fdm=marker
346 * vim<600: sw=4 ts=4