aboutsummaryrefslogtreecommitdiff
path: root/php/src/luigi-template.php
blob: 69e3fb874da5e2ffeea800b033b6715d1b69d0d9 (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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
<?php
declare(strict_types = 1);

namespace Luigi;

const VERSION = '0.4.2';

class Error extends \Exception {};

class UnknownTypeError extends Error {
  public $type,
         $name;

  public function __construct(string $type, string $name) {
    $this->type = $type;
    $this->name = $name;
    parent::__construct("unknown $type: $name");
  }
};

final class UnknownTemplateError extends UnknownTypeError {
  public function __construct(string $name) {
    parent::__construct('template', $name);
  }
};

final class UnknownFilterError extends UnknownTypeError {
  public function __construct(string $name) {
    parent::__construct('filter', $name);
  }
};

final class UnknownKeyError extends UnknownTypeError {
  public function __construct(string $name) {
    parent::__construct('key', $name);
  }
};

final class MissingFilterParameterError extends Error {
  public $filter_name;

  public function __construct(string $filter_name) {
    $this->filter_name = $filter_name;
    parent::__construct("missing required filter parameter for filter $filter_name");
  }
};

final class InvalidTemplateError extends Error {
  public $template;

  public function __construct(string $template) {
    $this->template = $template;
    parent::__construct("invalid template: $template");
  }
};

namespace Luigi;

final class RunContext {
  public $args,
         $filters;

  public function __construct(array $args, array $filters) {
    $this->args = $args;
    $this->filters = $filters;
  }
};

final class TemplateFilter {
  private $name,
          $args;

  public function __construct(string $name, array $args) {
    $this->name = $name;
    $this->args = $args;
  }

  public function run($v, array &$args, array &$filters) {
    if (!isset($filters[$this->name])) {
      throw new UnknownFilterError($this->name);
    }

    # get callback
    $cb = $filters[$this->name];

    # invoke callback, return result
    return $cb($v, $this->args, $args);
  }
};

namespace Luigi\Parser;

use Luigi\RunContext;
use Luigi

abstract class Token {
  public function run(array $args, array $filters) : string;
};

final class LiteralToken extends Token {
  private $val;

  public function __construct(string $val) {
    $this->val = $val;
  }

  public function run(array &$args, array &$filters) : string {
    return $this->val;
  }
};

final class FilterToken extends Token {
  private $key,
          $filters;

  public function __construct(string $key, array $filters) {
    $this->key = $key;
    $this->filters = $filters;
  }

  public function run(array &$args, array &$filters) : string {
    if (!isset($args[$this->key])) {
      throw new UnknownKeyError($this->key);
    }

    # get initial value
    $r = $args[$this->key];

    if ($this->filters && count($this->filters) > 0) {
      # pass value through filters
      $r = array_reduce($this->filters, function($r, $f) use (&$args, &$filters) {
        return $f->run($r, $args, $filters);
      }, $r);
    }

    # return result
    return $r;
  }
};

const TOKEN_RE = '/
  # 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';

const FILTER_RE = '/
  # match filter name
  (?<name>\S+)

  # match filter arguments (optional)
  (?<args>(\s*\S+)*)

  # optional trailing whitespace
  \s*
/mx';

const DELIM_FILTERS_RE = '/\s*\|\s*/m';

const DELIM_ARGS_RE = '/\s+/m';

function parse_filters(string $filters) : array {
  # split into individual filters
  $r = [];

  foreach (preg_split(DELIM_FILTERS_RE, $filters) as $f) {
    # trim whitespace
    $f = trim($f);

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

    # match filter
    $md = [];
    if (!preg_match(FILTER_RE, $f, $md)) {
      throw new UnknownFilterError($f);
    }

    # add filter to results
    $r[] = new TemplateFilter($md['name'], (count($md) > 2) ? preg_split(
      DELIM_ARGS_RE,
      trim($md['args'])
    ) : []);
  }

  # return results
  return $r;
}

function parse_template(string $template) : array {
  # build list of matches
  $matches = [];
  $num_matches = preg_match_all(TOKEN_RE, $template, $matches, PREG_SET_ORDER);

  # check for error
  if ($num_matches === false) {
    throw new InvalidTemplateError($template);
  }

  # map matches to tokens
  return array_map(function($m) {
    if ($m['key'] !== '') {
      # filter token
      return new FilterToken($m['key'], parse_filters($m['filters']));
    } else {
      # literal token
      return new LiteralToken($m['text']);
    }
  }, $matches);
}

namespace Luigi;

public $FILTERS = [
  'h' => function($s) {
    return htmlspecialchars($v, ENT_QUOTES);
  },

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

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

  'hash' => function($v, $args) {
    if (count($args) !== 1) {
      throw new MissingFilterParameterError('hash');
    }

    return hash($args[0], $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);
  },

  'key' => function($v, $args) {
    if (count($args) !== 1) {
      throw new MissingFilterParameterError('key');
    }

    # get key
    $key = $args[0];

    # make sure key exists
    if (!isset($v[$key])) {
      throw new UnknownKeyError($key);
    }

    # return key
    return $v[$key];
  },
];

final class Template {
  private $template,
          $filters,
          $tokens;

  public function __construct(
    string $template,
    array $custom_filters = []
  ) {
    global $FILTERS;

    $this->template = $template;
    $this->filters = count($custom_filters) ? $custom_filters : $FILTERS;

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

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

    return join('', array_map(function($token) use ($me, $args) {
      return $token->run($args, $this->filters);
    }, $this->tokens));
  }

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

public function run(
  string $template,
  array $args = [],
  array $filters = []
) : string {
  $t = new Template($template, $filters);
  return $t->run($args);
}

final class Cache implements \ArrayAccess {
  private $templates,
          $filters,
          $lut = [];

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

  public function offsetExists($key) : bool {
    return isset($this->templates[$key]);
  }

  public function offsetGet($key) {
    if (isset($this->lut[$key])) {
      return $this->lut[$key];
    } else if (isset($this->templates[$key]) {
      $this->lut[$key] = new Template($this->templates[$key], $this->filters);
      return $this->lut[$key];
    } else {
      throw new UnknownTemplateError($key);
    }
  }

  public function offsetUnset($key) {
    delete($this->lut[$key]);
    delete($this->templates[$key]);
  }

  public function offsetSet($key, $val) : bool {
    delete($this->lut[$key]);
    $this->templates[$key] = $val;
    return isset($this->templates[$key]);
  }


  public function run(string $key, array $args = []) : string {
    return $this->offsetGet($key)->run($args);
  }
};