/
EchoExtension.php
478 lines (399 loc) · 15.7 KB
/
EchoExtension.php
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
<?php
namespace Admingenerator\GeneratorBundle\Twig\Extension;
class EchoExtension extends \Twig_Extension
{
protected $loader;
protected $controller;
protected $blockNames = array();
public function __construct(\Twig_LoaderInterface $loader)
{
$this->loader = $loader;
}
public function setController($controller)
{
$this->controller = $controller;
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return array(
'echo_twig' => new \Twig_Function_Method($this, 'getEchoTwig'),
'echo_block' => new \Twig_Function_Method($this, 'getEchoBlock'),
'echo_endblock' => new \Twig_Function_Method($this, 'getEchoEndBlock'),
'echo_for' => new \Twig_Function_Method($this, 'getEchoFor'),
'echo_endfor' => new \Twig_Function_Method($this, 'getEchoEndFor'),
'echo_raw' => new \Twig_Function_Method($this, 'getEchoRaw'),
'echo_endraw' => new \Twig_Function_Method($this, 'getEchoEndRaw'),
'echo_extends' => new \Twig_Function_Method($this, 'getEchoExtends'),
'echo_if' => new \Twig_Function_Method($this, 'getEchoIf'),
'echo_if_granted' => new \Twig_Function_Method($this, 'getEchoIfGranted'),
'echo_else' => new \Twig_Function_Method($this, 'getEchoElse'),
'echo_elseif' => new \Twig_Function_Method($this, 'getEchoElseIf'),
'echo_endif' => new \Twig_Function_Method($this, 'getEchoEndIf'),
'echo_path' => new \Twig_Function_Method($this, 'getEchoPath'),
'echo_set' => new \Twig_Function_Method($this, 'getEchoSet'),
'echo_trans' => new \Twig_Function_Method($this, 'getEchoTrans'),
'echo_twig_assoc' => new \Twig_Function_Method($this, 'getEchoTwigAssoc'),
'echo_twig_filter' => new \Twig_Function_Method($this, 'getEchoTwigFilter'),
'echo_include' => new \Twig_Function_Method($this, 'getEchoInclude'),
'echo_render' => new \Twig_Function_Method($this, 'getEchoRender'),
);
}
public function getFilters()
{
return array(
'as_php' => new \Twig_Filter_Method($this, 'asPhp'),
'convert_as_form' => new \Twig_Filter_Method($this, 'convertAsForm'),
'php_name' => new \Twig_Filter_Method($this, 'phpName'),
);
}
/**
* Try to convert options of form given as string from yaml to a good object
*
* eg type option for collection type
*
* @param string $options the string as php
* @param string $formType the form type
*
* @return string the new options
*/
public function convertAsForm($options, $formType)
{
$options = preg_replace("/'__php\((.+?)\)'/i", '$1', $options, -1, $count);
if ('collection' == $formType || 'upload' == $formType) {
preg_match("/'type' => '(.+?)'/i", $options, $matches);
if (count($matches) > 0) {
$pattern_formtype = '/^\\\\+(([a-zA-Z_]\w*\\\\+)*)([a-zA-Z_]\w*)$/';
// Sanity check: prepend with "new" and append with "()"
// only if type option is a Fully qualified name
if (preg_match($pattern_formtype, $matches[1])) {
$options = str_replace("'type' => '".$matches[1]."'", '\'type\' => new '.stripslashes($matches[1]).'()', $options);
}
}
}
if ('model' == $formType) {
preg_match("/'query' => '(.+?)',/i", $options, $matches);
if (count($matches) > 0) {
$options = str_replace("'query' => '".$matches[1]."'", '\'query\' => '.stripslashes($matches[1]), $options);
}
}
if ('choice' == $formType || 'double_list' == $formType) {
preg_match("/'choices' => '(.+?)',/i", $options, $matches);
if (count($matches) > 0) {
$options = str_replace("'choices' => '".$matches[1]."'", '\'choices\' => '.stripslashes($matches[1]), $options);
}
}
if ('form_widget'== $formType) { // For type wich are not strings
preg_match("/\'(.*)Type/", $options, $matches);
if (count($matches) > 0) {
return 'new '.stripslashes($matches[1]).'Type()';
}
}
return $options;
}
public function asPhp($variable)
{
if (!is_array($variable)) {
return $this->export($variable);
}
$str = $this->export($variable);
preg_match_all('/[^> ]+::__set_state\(array\((.+),\'loaded/i', $str, $matches);
if (isset($matches[1][0])) {
$params = 'return array('.$matches[1][0].')';
$params = eval($params. '?>');
$str_param = '';
foreach ($params as $p) {
if ('' !== $str_param) {
$str_param .= ', ';
}
$str_param .= $this->export($p);
}
$str = preg_replace("/([^> ]+)::__set_state\(/i", ' new \\\$0', $str);
$str = str_replace('::__set_state', '', $str);
$str = str_replace('array('.$matches[1][0].',\'loaded\' => false, )', $str_param, $str);
}
return $str;
}
/**
* Converts string into valid PHP function name
*
* @param string $str
* @return string
*/
public function phpName($str)
{
$str = preg_replace('/[^\w]+/', '', $str);
return $str;
}
public function export($variable)
{
return str_replace(array("\n", 'array (', ' '), array('', 'array(', ''), var_export($variable, true));
}
/**
* Reads parameters from subject and removes parameter bag from string.
*
* @return array
* [string] -> string for echo trans
* [params] -> parameters for echo trans
*
* @return false if subject did not match any of following patterns
*
* ##############################
* Backwards compability pattern:
*
* replaces twig tags {{ parameter_name }} with parameters.
*
* example: You're editing {{ Book.title }} written by {{ Book.author.name }}!
*
* results in:
* string -> You're editing %Book.title% written by %Book.author.name%!
* params ->
* [Book.title] -> Book.title
* [Book.author.name] -> Book.author.name
*
* ###################################
* Feature - key-value syntax pattern:
* |{ %param_key%: param_value, %param_key2%: param_value2, %param_key3%: param_value3 }|
*
* where param_key and param_value consist of any number a-z, A-Z, 0-9 or . (dot) characters
*
* example: You're editing %book% written by %author%!|{ %book%: Book.title, %author%: Book.author.name }|
* results in:
* string -> You're editing %book% written by %author%!
* params ->
* [book] -> Book.title
* [author] -> Book.author.name
*
* example: book.edit.title|{ %book%: Book.title, %author%: Book.author.name }| *
* results in:
* string -> book.edit.title
* params ->
* [book] -> Book.title
* [author] -> Book.author.name
*
* ###################################
* Feature - abbreviated syntax pattern:
* |{ param_value, param_value2, param_value3 }|
*
* where param_value consists of any number a-z, A-Z, 0-9 or . (dot) characters
*
* example: You're editing %Book.title% written by %Book.author.name%!|{ Book.title, Book.author.name }|
* results in:
* string -> You're editing %Book.title% written by %Book.author.name%!
* params ->
* [Book.title] -> Book.title
* [Book.author.name] -> Book.author.name
*
* example: book.edit.title|{ Book.title, Book.author.name }|
* results in:
* string -> book.edit.title
* params ->
* [Book.title] -> Book.title
* [Book.author.name] -> Book.author.name
*/
private function getParameterBag($subject)
{
# Backwards compability - replace twig tags with parameters
$pattern_bc = '/\{\{\s(?<param>[a-zA-Z0-9.]+)\s\}\}+/';
if (preg_match_all($pattern_bc, $subject, $match_params)) {
$string = preg_filter($pattern_bc, '%\1%', $subject);
$param = array();
foreach ($match_params['param'] as $value) { $param[$value] = $value; }
return array(
'string' => $string,
'params' => $param
);
}
# Feature - read key/value syntax parameters
$pattern_string = '/^(?<string>[^|]+)(?<parameter_bag>\|\{(\s?%[a-zA-Z0-9.]+%:\s[a-zA-Z0-9.]+,?\s?)+\s?\}\|)\s*$/';
$pattern_params = '/(?>(?<=(\|\{\s|.,\s))%(?<key>[a-zA-Z0-9.]+)%:\s(?<value>[a-zA-Z0-9.]+)(?=(,\s.|\s\}\|)))+/';
if ( preg_match($pattern_string, $subject, $match_string) ) {
$string = $match_string['string'];
$parameter_bag = $match_string['parameter_bag'];
$param = array();
preg_match_all($pattern_params, $parameter_bag, $match_params, PREG_SET_ORDER);
foreach ($match_params as $match) { $param[$match['key']] = $match['value']; }
return array(
'string' => $string,
'params' => $param
);
}
# Feature - read abbreviated syntax parameters
$abbreviated_pattern_string = '/^(?<string>[^|]+)(?<parameter_bag>\|\{(\s?[a-zA-Z0-9.]+,?\s?)+\s?\}\|)\s*$/';
$abbreviated_pattern_params = '/(?>(?<=(\|\{\s|.,\s))(?<param>[a-zA-Z0-9.]+)(?=(,\s.|\s\}\|)))+?/';
if ( preg_match($abbreviated_pattern_string, $subject, $match_string)) {
$string = $match_string['string'];
$parameter_bag = $match_string['parameter_bag'];
$param = array();
preg_match_all($abbreviated_pattern_params, $parameter_bag, $match_params);
foreach ($match_params['param'] as $value) { $param[$value] = $value; }
return array(
'string' => $string,
'params' => $param
);
}
# If subject does not match any pattern, return false
return false;
}
public function getEchoTrans($str, array $parameters=array(), $catalog = 'Admingenerator')
{
$echo_parameters=NULL;
$bag_parameters=array();
if ($parameterBag = $this->getParameterBag($str)) {
$str = $parameterBag['string'];
$bag_parameters = $parameterBag['params'];
}
if (!empty($parameters) || !empty($bag_parameters)) {
$echo_parameters="with {";
foreach ($parameters as $key => $value) {
$echo_parameters.= "'%".$key."%': '".$value."',";
}
foreach ($bag_parameters as $key => $value) {
$echo_parameters.= "'%".$key."%': ".$value.",";
}
$echo_parameters.="} ";
}
return '{% trans '.$echo_parameters.'from "'.$catalog.'" %}'.$str.'{% endtrans %}';
}
public function getEchoSet($var, $value, $value_as_string = true)
{
if ($value_as_string) {
return strtr('{% set %%var%% = "%%value%%" %}',array('%%var%%' => $var, '%%value%%' => $value));
} else {
return strtr('{% set %%var%% = %%value%% %}',array('%%var%%' => $var, '%%value%%' => $value));
}
}
public function getEchoPath($path, $params = null, $filters = null)
{
if (null === $params) {
return (null === $filters)
? strtr('{{ path("%%path%%") }}', array('%%path%%' => $path))
: strtr('{{ path("%%path%%")|%%filters%% }}', array('%%path%%' => $path, '%%filters%%' => (is_array($filters) ? implode('|', $filters) : $filters) ));
}
$params = preg_replace('/\{\{\s+?([\w\.]+)\s+?\}\}/i', '$1', $params);
return (null === $filters)
? strtr('{{ path("%%path%%", %%params%%) }}', array('%%path%%' => $path, '%%params%%' => $params))
: strtr('{{ path("%%path%%", %%params%%)|%%filters%% }}', array('%%path%%' => $path, '%%params%%' => $params, '%%filters%%' => (is_array($filters) ? implode('|', $filters) : $filters) ));
}
public function getEchoIfGranted($credentials, $modelName = null)
{
if (null === $modelName) {
return $this->getEchoIf('is_expr_granted(\''.$credentials.'\')');
}
return $this->getEchoIf('is_expr_granted(\''.$credentials.'\', '.$modelName.')');
}
public function getEchoIf($condition)
{
if ( is_bool( $condition ) ) {
$condition = intval( $condition );
}
return str_replace('%%condition%%', $condition, '{% if %%condition%% %}');
}
public function getEchoElseIf($condition)
{
if ( is_bool( $condition ) ) {
$condition = intval( $condition );
}
return str_replace('%%condition%%', $condition, '{% elseif %%condition%% %}');
}
public function getEchoElse()
{
return '{% else %}';
}
public function getEchoEndIf()
{
return '{% endif %}';
}
public function getEchoTwig($str)
{
return sprintf('{{ %s }}', $str);
}
public function getEchoTwigFilter($str, $filters = null, $asString = false)
{
if (null === $filters) {
return $this->getEchoTwig($str);
}
return strtr('{{ %%str%%|%%filters%% }}', array('%%str%%' => $asString ? '"'.$str.'"' : $str, '%%filters%%' => (is_array($filters) ? implode('|', $filters) : $filters) ));
}
public function getEchoBlock($name)
{
$this->blockNames[] = $name;
return str_replace('%%name%%', $name, '{% block %%name%% %}');
}
public function getEchoExtends($name)
{
return str_replace('%%name%%', $name, '{% extends "%%name%%" %}');
}
public function getEchoEndBlock()
{
return str_replace('%%name%%', array_pop($this->blockNames), '{% endblock %%name%% %}');
}
public function getEchoFor($object, $in)
{
return strtr('{% for %%object%% in %%in%% %}', array('%%object%%' => $object, '%%in%%' => $in ));
}
public function getEchoEndFor()
{
return '{% endfor %}';
}
public function getEchoRaw()
{
return '{% raw %}';
}
public function getEchoEndRaw()
{
return '{% endraw %}';
}
/**
* Converts an assoc array to a twig array expression (string) .
* Only in case a value contains '{{' and '}}' the value won't be
* wrapped in quotes.
*
* An array like:
* <code>
* $array = array('a' => 'b', 'c' => 'd');
* </code>
*
* Will be converted to:
* <code>
* "{ a: 'b', c: 'd' }"
* </code>
*
* @return string The parameters to be used in a URL
*/
public function getEchoTwigAssoc(array $arr)
{
$contents = array();
foreach ($arr as $key => $value) {
if (!strstr($value, '{{')
|| !strstr($value, '}}'))
{
$value = "'$value'";
} else {
$value = trim(str_replace(array('{{', '}}'), '', $value));
}
$contents[] = "$key: $value";
}
return '{ ' . implode(', ', $contents) . ' }';
}
public function getEchoInclude($twig)
{
return '{% include "'.$twig.'" %}';
}
public function getEchoRender($controller, array $params = array())
{
$params = $this->getEchoTwigAssoc($params);
return '{% render(controller("'.$controller.'", '.$params.')) %}';
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'echo';
}
}