summaryrefslogtreecommitdiff
path: root/php/luigi-template.php
blob: cec1ff6b1a3cbf75df0b8d821a14123c8ebb5d6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<?php

namespace Luigi;

const VERSION = '0.4.0';

final class Error extends \Exception {};

final class Filters {
  private static $filters = null;

  public static function init() {
    if (self::$filters !== null)
      return;

    self::$filters = array(
      'h' => function($s) {
        return htmlspecialchars($v);
      },

      'u' => function($s) {
        return urlencode($v);
      },

      'json' => function($v) {
        return json_encode($v);
      },

      'hash' => function($v, $args) {
        $algo = (count($args) == 1) ? $args[0] : 'md5';
        return hash($algo, $v);
      },

      'base64' => function($v) {
        return base64_encode($v);
      },

      'nl2br' => function($v) {
        return nl2br($v);
      },

      'uc' => function($v) {
        return strtoupper($v);
      },

      'lc' => function($v) {
        return strtolower($v);
      },

      'trim' => function($v) {
        return trim($v);
      },

      'rtrim' => function($v) {
        return rtrim($v);
      },

      'ltrim' => function($v) {
        return ltrim($v);
      },

      's' => function($v) {
        return ($v == 1) ? '' : 's';
      },

      'strlen' => function($v) {
        return strlen($v);
      },

      'count' => function($v) {
        return count($v);
      },
    );
  }

  public static function get($key) {
    self::init();

    if (!isset(self::$filters[$key]))
      throw new Error("unknown filter: $key");

    return self::$filters[$key];
  }

  public static function add(array $filters) {
    self::init();
    self::$filters = array_merge(self::$filters, $filters);
  }
};

final class LegacyParser {
  private static $RES = array(
    'action' => '/
      # match opening brace
      %\{\s*

      # match key
      ([\w_-]+)
    
      # match filter(s)
      ((\s*\|\s*\w+\s*(\([\w\s,-]+\))?)*)

      # match closing brace
      \}
      
      # or match up all non-% chars or a single % char
      | ([^%]* | %)
    /mx',

    'filter' => '/
      # match filter name
      ([\w_-]+)
    
      # optional trailing whitespace
      \s*
    
      # optional filter arguments
      (\(([\w\s_,-]+)\))?
    /mx',
  );

  public static function parse_template($template) {
    # build list of matches
    $matches = array();
    $num_matches = preg_match_all(
      self::$RES['action'],
      $template,
      $matches,
      PREG_SET_ORDER
    );
  
    # check for error
    if ($num_matches === false)
      throw new Error('error matching template');
  
    # walk over matches and build list of actions
    $r = array_map(function($m) {
      if ($m[1] !== '') {
        #  key and filters
        return array(
          'type'    => 'action',
          'key'     => $m[1],
          'filters' => self::parse_filters($m[2]),
        );
      } else {
        # literal text
        return array(
          'type' => 'text',
          'text' => $m[5],
        );
      }
    }, $matches);

    # return result
    return $r;
  }

  public static function parse_filters($filters) {
    # split into individual filters
    $r = array();
    foreach (preg_split('/\s*\|\s*/', $filters) as $f) {
      # skip empty filters
      if (!$f)
        continue;

      # match filter
      $md = array();
      if (!preg_match(self::$RES['filter'], $f, $md))
        throw new Error("invalid filter: $f");

      # add filter to results
      $r[] = array(
        # filter name
        'name' => $md[1],

        # filter arguments
        'args' => (count($md) > 2) ? preg_split(
          '/\s*,\s*/', 
          trim($md[3])
        ) : array(),
      );
    }

    # return results
    return $r;
  }
};

final class Parser {
  private static $RES = array(
    'action' => '/
      # match opening brace
      %\{
      
      # match optional whitespace
      \s*

      # match key
      (?<key>[^\s\|\}]+)

      # match filter(s)
      (?<filters>(\s*\|(\s*[^\s\|\}]+)+)*)

      # match optional whitespace
      \s*
    
      # match closing brace
      \}
      
      # or match up all non-% chars or a single % char
      | (?<text>[^%]* | %)
    /mx',

    'filter' => '/
      # match filter name
      (?<name>\S+)
    
      # match filter arguments (optional)
      (?<args>(\s*\S+)*)
    
      # optional trailing whitespace
      \s*
    /mx',

    'delim_filters' => '/\s*\|\s*/m',
    'delim_args' => '/\s+/m',
  );

  public static function parse_template($template) {
    # build list of matches
    $matches = array();
    $num_matches = preg_match_all(
      self::$RES['action'],
      $template,
      $matches,
      PREG_SET_ORDER
    );

    # check for error
    if ($num_matches === false)
      throw new Error("invalid template: $template");
  
    # walk over matches and build list of actions
    $r = array_map(function($m) {
      if ($m['key'] !== '') {
        #  key and filters
        return array(
          'type'    => 'action',
          'key'     => $m['key'],
          'filters' => self::parse_filters($m['filters']),
        );
      } else {
        # literal text
        return array(
          'type' => 'text',
          'text' => $m['text'],
        );
      }
    }, $matches);

    # return result
    return $r;
  }

  public static function parse_filters($filters) {
    # split into individual filters
    $r = array();
    foreach (preg_split(self::$RES['delim_filters'], $filters) as $f) {
      # trim whitespace
      $f = trim($f);

      # skip empty filters
      if (!$f)
        continue;

      # match filter
      $md = array();
      if (!preg_match(self::$RES['filter'], $f, $md))
        throw new Error("invalid filter: $f");

      # add filter to results
      $r[] = array(
        # filter name
        'name' => $md['name'],

        # filter arguments
        'args' => (count($md) > 2) ? preg_split(
          self::$RES['delim_args'],
          trim($md['args'])
        ) : array(),
      );
    }

    # return results
    return $r;
  }
};

final class Template {
  private $template, $actions, $o;

  public function __construct($template, array $o = array()) {
    $this->template = $template;
    $this->o = $o;

    # parse template into list of actions
    $this->actions = Parser::parse_template($template);
  }

  public function run(array $args = array()) {
    # php sucks
    $me = $this;

    return join('', array_map(function($row) use ($me, $args) {
      if ($row['type'] == 'text') {
        # literal text
        return $row['text'];
      } else if ($row['type'] == 'action') {
        # template key (possibly with filters)

        # check value
        if (!isset($args[$row['key']]))
          throw new Error("unknown key: {$row['key']}");

        # pass value through filters and return result
        return array_reduce($row['filters'], function($r, $f) use ($me, $args) {
          # get filter
          $fn = Filters::get($f['name']);
        
          # call filter and return result
          return call_user_func($fn, $r, $f['args'], $args, $me);
        }, $args[$row['key']]);
      } else {
        # should never be reached
        throw new Error("unknown action type: {$row['type']}");
      }
    }, $this->actions));
  }

  public static function run_once($str, array $args = array()) {
    $t = new Template($str);
    return $t->run($args);
  }
};

final class Cache {
  private $templates, $o, $lut = array();

  public function __construct(array $templates, array $o = array()) {
    $this->templates = $templates;
    $this->o = $o;
  }

  public function get($key) {
    if (!isset($this->lut[$key])) {
      if (!isset($this->templates[$key]))
        throw new Error("unknown template: $key");

      # lazy-load template
      $this->lut[$key] = new Template($this->templates[$key], $this->o);
    }

    # return result
    return $this->lut[$key];
  }

  public function run($key, array $args = array()) {
    return $this->get($key)->run($args);
  }
};