-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathJavaScript.php
471 lines (402 loc) · 11.3 KB
/
JavaScript.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
<?php
/**
* @package s9e\TextFormatter
* @copyright Copyright (c) The s9e authors
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace s9e\TextFormatter\Configurator;
use ReflectionClass;
use s9e\TextFormatter\Configurator;
use s9e\TextFormatter\Configurator\Helpers\AVTHelper;
use s9e\TextFormatter\Configurator\Helpers\ConfigHelper;
use s9e\TextFormatter\Configurator\JavaScript\CallbackGenerator;
use s9e\TextFormatter\Configurator\JavaScript\Code;
use s9e\TextFormatter\Configurator\JavaScript\ConfigOptimizer;
use s9e\TextFormatter\Configurator\JavaScript\Dictionary;
use s9e\TextFormatter\Configurator\JavaScript\Encoder;
use s9e\TextFormatter\Configurator\JavaScript\FunctionCache;
use s9e\TextFormatter\Configurator\JavaScript\Hasher;
use s9e\TextFormatter\Configurator\JavaScript\HintGenerator;
use s9e\TextFormatter\Configurator\JavaScript\Minifier;
use s9e\TextFormatter\Configurator\JavaScript\Minifiers\Noop;
use s9e\TextFormatter\Configurator\JavaScript\RegexpConvertor;
use s9e\TextFormatter\Configurator\JavaScript\StylesheetCompressor;
use s9e\TextFormatter\Configurator\RendererGenerators\XSLT;
class JavaScript
{
/**
* @var CallbackGenerator
*/
protected $callbackGenerator;
/**
* @var array Configuration, filtered for JavaScript
*/
protected $config;
/**
* @var ConfigOptimizer
*/
protected $configOptimizer;
/**
* @var Configurator Configurator this instance belongs to
*/
protected $configurator;
/**
* @var Encoder
*/
public $encoder;
/**
* @var array List of methods and properties to be exported in the s9e.TextFormatter object
*/
public $exports = [
'disablePlugin',
'disableTag',
'enablePlugin',
'enableTag',
'getLogger',
'parse',
'preview',
'registeredVars',
'setNestingLimit',
'setParameter',
'setTagLimit'
];
public FunctionCache $functionCache;
/**
* @var HintGenerator
*/
protected $hintGenerator;
/**
* @var Minifier Instance of Minifier used to minify the JavaScript parser
*/
protected $minifier;
/**
* @var XSLT Renderer generator used to generate the live preview's stylesheet
*/
public XSLT $rendererGenerator;
/**
* @var StylesheetCompressor
*/
protected $stylesheetCompressor;
/**
* @var string Stylesheet used for rendering
*/
protected $xsl;
/**
* Constructor
*
* @param Configurator $configurator Configurator
*/
public function __construct(Configurator $configurator)
{
$this->encoder = new Encoder;
$this->callbackGenerator = new CallbackGenerator;
$this->configOptimizer = new ConfigOptimizer($this->encoder);
$this->configurator = $configurator;
$this->functionCache = new FunctionCache;
$this->hintGenerator = new HintGenerator;
$this->rendererGenerator = new XSLT;
$this->stylesheetCompressor = new StylesheetCompressor;
$this->rendererGenerator->normalizer->remove('RemoveLivePreviewAttributes');
}
/**
* Return the cached instance of Minifier (creates one if necessary)
*
* @return Minifier
*/
public function getMinifier()
{
if (!isset($this->minifier))
{
$this->minifier = new Noop;
}
return $this->minifier;
}
/**
* Get a JavaScript parser
*
* @param array $config Config array returned by the configurator
* @return string JavaScript parser
*/
public function getParser(?array $config = null)
{
$this->configOptimizer->reset();
// Get the stylesheet used for rendering
$this->xsl = $this->rendererGenerator->getXSL($this->configurator->rendering);
// Prepare the parser's config
$this->config = $config ?? $this->configurator->asConfig();
$this->config = ConfigHelper::filterConfig($this->config, 'JS');
$this->config = $this->callbackGenerator->replaceCallbacks($this->config);
// Get the parser's source and inject its config
$src = $this->getHints() . $this->injectConfig($this->getSource());
// Export the public API
$src .= "if (!window['s9e']) window['s9e'] = {};\n" . $this->getExports();
// Minify the source
$src = $this->getMinifier()->get($src);
// Wrap the source in a function to protect the global scope
$src = '(function(){' . $src . '})();';
return $src;
}
/**
* Set the cached instance of Minifier
*
* Extra arguments will be passed to the minifier's constructor
*
* @param string|Minifier $minifier Name of a supported minifier, or an instance of Minifier
* @return Minifier The new minifier
*/
public function setMinifier($minifier)
{
if (is_string($minifier))
{
$className = __NAMESPACE__ . '\\JavaScript\\Minifiers\\' . $minifier;
// Pass the extra argument to the constructor, if applicable
$args = array_slice(func_get_args(), 1);
if (!empty($args))
{
$reflection = new ReflectionClass($className);
$minifier = $reflection->newInstanceArgs($args);
}
else
{
$minifier = new $className;
}
}
$this->minifier = $minifier;
return $minifier;
}
//==========================================================================
// Internal
//==========================================================================
/**
* Encode a PHP value into an equivalent JavaScript representation
*
* @param mixed $value Original value
* @return string JavaScript representation
*/
protected function encode($value)
{
return $this->encoder->encode($value);
}
/**
* Generate and return the public API
*
* @return string JavaScript Code
*/
protected function getExports()
{
if (empty($this->exports))
{
return '';
}
$exports = [];
foreach ($this->exports as $export)
{
$exports[] = "'" . $export . "':" . $export;
}
sort($exports);
return "window['s9e']['TextFormatter'] = {" . implode(',', $exports) . '};';
}
/**
* @return string Function cache serialized as a JavaScript object
*/
protected function getFunctionCache(): string
{
$this->functionCache->addFromXSL($this->xsl);
return $this->functionCache->getJSON();
}
/**
* Generate a HINT object that contains informations about the configuration
*
* @return string JavaScript Code
*/
protected function getHints()
{
$this->hintGenerator->setConfig($this->config);
$this->hintGenerator->setPlugins($this->configurator->plugins);
$this->hintGenerator->setXSL($this->xsl);
return $this->hintGenerator->getHints();
}
/**
* Return the plugins' config
*
* @return Dictionary
*/
protected function getPluginsConfig()
{
$plugins = new Dictionary;
foreach ($this->config['plugins'] as $pluginName => $pluginConfig)
{
if (!isset($pluginConfig['js']))
{
// Skip this plugin
continue;
}
$js = $pluginConfig['js'];
unset($pluginConfig['js']);
// Not needed in JavaScript
unset($pluginConfig['className']);
// Ensure that quickMatch is UTF-8 if present
if (isset($pluginConfig['quickMatch']))
{
// Well-formed UTF-8 sequences
$valid = [
'[[:ascii:]]',
// [1100 0000-1101 1111] [1000 0000-1011 1111]
'[\\xC0-\\xDF][\\x80-\\xBF]',
// [1110 0000-1110 1111] [1000 0000-1011 1111]{2}
'[\\xE0-\\xEF][\\x80-\\xBF]{2}',
// [1111 0000-1111 0111] [1000 0000-1011 1111]{3}
'[\\xF0-\\xF7][\\x80-\\xBF]{3}'
];
$regexp = '#(?>' . implode('|', $valid) . ')+#';
// Keep only the first valid sequence of UTF-8, or unset quickMatch if none is found
if (preg_match($regexp, $pluginConfig['quickMatch'], $m))
{
$pluginConfig['quickMatch'] = $m[0];
}
else
{
unset($pluginConfig['quickMatch']);
}
}
/**
* @var array Keys of elements that are kept in the global scope. Everything else will be
* moved into the plugin's parser
*/
$globalKeys = [
'quickMatch' => 1,
'regexp' => 1,
'regexpLimit' => 1
];
$globalConfig = array_intersect_key($pluginConfig, $globalKeys);
$localConfig = array_diff_key($pluginConfig, $globalKeys);
if (isset($globalConfig['regexp']) && !($globalConfig['regexp'] instanceof Code))
{
$globalConfig['regexp'] = new Code(RegexpConvertor::toJS($globalConfig['regexp'], true));
}
$globalConfig['parser'] = new Code(
'/**
* @param {string} text
* @param {!Array.<!Array>} matches
*/
function(text, matches)
{
const config=' . $this->encode($localConfig) . ';
' . $js . '
}'
);
$plugins[$pluginName] = $globalConfig;
}
return $plugins;
}
/**
* Return the registeredVars config
*
* @return Dictionary
*/
protected function getRegisteredVarsConfig()
{
$registeredVars = $this->config['registeredVars'];
// Remove cacheDir from the registered vars. Not only it is useless in JavaScript, it could
// leak some informations about the server
unset($registeredVars['cacheDir']);
return new Dictionary($registeredVars);
}
/**
* Return the root context config
*
* @return array
*/
protected function getRootContext()
{
return $this->config['rootContext'];
}
/**
* Return the parser's source
*
* @return string
*/
protected function getSource()
{
$rootDir = __DIR__ . '/..';
$src = '';
// If getLogger() is not exported we use a dummy Logger that can be optimized away
$logger = (in_array('getLogger', $this->exports, true)) ? 'Logger.js' : 'NullLogger.js';
// Prepare the list of files
$files = glob($rootDir . '/Parser/AttributeFilters/*.js');
$files[] = $rootDir . '/Parser/utils.js';
$files[] = $rootDir . '/Parser/FilterProcessing.js';
$files[] = $rootDir . '/Parser/' . $logger;
$files[] = $rootDir . '/Parser/Tag.js';
$files[] = $rootDir . '/Parser.js';
// Append render.js if we export the preview method
if (in_array('preview', $this->exports, true))
{
$files[] = $rootDir . '/render.js';
$src .= 'const xsl=' . $this->getStylesheet() . ";\n";
$src .= 'let functionCache=' . $this->getFunctionCache() . ";\n";
}
$src .= implode("\n", array_map('file_get_contents', $files));
return $src;
}
/**
* Return the JavaScript representation of the stylesheet
*
* @return string
*/
protected function getStylesheet()
{
return $this->stylesheetCompressor->encode($this->xsl);
}
/**
* Return the tags' config
*
* @return Dictionary
*/
protected function getTagsConfig()
{
// Prepare a Dictionary that will preserve tags' names
$tags = new Dictionary;
foreach ($this->config['tags'] as $tagName => $tagConfig)
{
if (isset($tagConfig['attributes']))
{
// Make the attributes array a Dictionary, to preserve the attributes' names
$tagConfig['attributes'] = new Dictionary($tagConfig['attributes']);
}
$tags[$tagName] = $tagConfig;
}
return $tags;
}
/**
* Inject the parser config into given source
*
* @param string $src Parser's source
* @return string Modified source
*/
protected function injectConfig($src)
{
$config = array_map(
$this->encode(...),
$this->configOptimizer->optimize(
[
'plugins' => $this->getPluginsConfig(),
'registeredVars' => $this->getRegisteredVarsConfig(),
'rootContext' => $this->getRootContext(),
'tagsConfig' => $this->getTagsConfig()
]
)
);
$src = preg_replace_callback(
'/(\\n(?:cons|le)t (' . implode('|', array_keys($config)) . '))(;)/',
function ($m) use ($config)
{
return $m[1] . '=' . $config[$m[2]] . $m[3];
},
$src
);
// Prepend the deduplicated objects
$src = $this->configOptimizer->getVarDeclarations() . $src;
return $src;
}
}