-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathJavascriptBuilder.php
More file actions
384 lines (345 loc) · 12.3 KB
/
JavascriptBuilder.php
File metadata and controls
384 lines (345 loc) · 12.3 KB
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
<?php
/**
* Javascript aggregator and builder class
*
* PHP version 5
*
* LICENSE
*
* This source file is subject to BSD 3-Clause License that is bundled
* with this package in the file LICENSE and available at the URL
* https://raw.githubusercontent.com/pear/HTML_QuickForm2/trunk/docs/LICENSE
*
* @category HTML
* @package HTML_QuickForm2
* @author Alexey Borzov <avb@php.net>
* @author Bertrand Mansion <golgote@mamasam.com>
* @copyright 2006-2025 Alexey Borzov <avb@php.net>, Bertrand Mansion <golgote@mamasam.com>
* @license https://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
* @link https://pear.php.net/package/HTML_QuickForm2
*/
// pear-package-only /**
// pear-package-only * Exception classes for HTML_QuickForm2
// pear-package-only */
// pear-package-only require_once 'HTML/QuickForm2/Exception.php';
/**
* Javascript aggregator and builder class
*
* @category HTML
* @package HTML_QuickForm2
* @author Alexey Borzov <avb@php.net>
* @author Bertrand Mansion <golgote@mamasam.com>
* @license https://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
* @version Release: @package_version@
* @link https://pear.php.net/package/HTML_QuickForm2
*/
class HTML_QuickForm2_JavascriptBuilder
{
/**
* Client-side rules
* @var array<string, string[]>
*/
protected $rules = [];
/**
* Elements' setup code
* @var array<string, string[]>
*/
protected $scripts = [];
/**
* Whether to generate a validator object for the form if no rules are present
*
* Needed when the form contains an empty repeat element
*
* @var array<string, bool>
*/
protected $forceValidator = [];
/**
* Javascript libraries
* @var array<string, array{file: string, webPath: ?string, absPath: ?string}>
*/
protected $libraries = [
'base' => [
'file' => 'quickform.js',
'webPath' => null,
'absPath' => null
]
];
/**
* Default web path to JS library files
* @var string
*/
protected $defaultWebPath;
/**
* Default filesystem path to JS library files
* @var string
*/
protected $defaultAbsPath;
/**
* Current form ID
* @var string
*/
protected $formId;
/**
* Constructor, sets default web path to JS library files and default filesystem path
*
* @param string $defaultWebPath default web path to JS library files
* (to use in <script src="...">)
* @param string $defaultAbsPath default filesystem path to JS library files
* (to inline these files into the page), this is set to a package
* subdirectory of PEAR data_dir if not given
*/
public function __construct($defaultWebPath = 'js/', $defaultAbsPath = null)
{
$this->defaultWebPath = $defaultWebPath;
if (null === $defaultAbsPath) {
$defaultAbsPath = '@data_dir@' . DIRECTORY_SEPARATOR . 'HTML_QuickForm2'
. DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR;
// Not a PEAR installation, use relative path
if (0 === strpos($defaultAbsPath, '@' . 'data_dir@')) {
if (false === $defaultAbsPath = realpath(__DIR__ . '/../../data/js')) {
throw new HTML_QuickForm2_Exception(
'Unable to locate directory containing JavaScript files, please provide one explicitly'
);
}
$defaultAbsPath .= DIRECTORY_SEPARATOR;
}
}
$this->defaultAbsPath = $defaultAbsPath;
}
/**
* Adds a Javascript library file to the list
*
* @param string $name name to reference the library by
* @param string $fileName file name, without path
* @param string $webPath path relative to web root to reference in <script src="">,
* $defaultWebPath will be used if not given
* @param string $absPath filesystem path where the file resides, used when inlining
* libraries, $defaultAbsPath will be used if not given
*/
public function addLibrary($name, $fileName, $webPath = null, $absPath = null)
{
$this->libraries[strtolower($name)] = [
'file' => $fileName, 'webPath' => $webPath, 'absPath' => $absPath
];
}
/**
* Returns Javascript libraries
*
* @param bool $inline whether to return a list of library file names
* or contents of files
* @param bool $addScriptTags whether to enclose the results in <script> tags
*
* @return string|array
*/
public function getLibraries($inline = false, $addScriptTags = true)
{
if (!$inline) {
$ret = [];
foreach ($this->libraries as $name => $library) {
$path = !empty($library['webPath'])? $library['webPath']: $this->defaultWebPath;
if ('/' != substr($path, -1)) {
$path .= '/';
}
$ret[$name] = $addScriptTags
? "<script type=\"text/javascript\" src=\"{$path}{$library['file']}\"></script>"
: $path . $library['file'];
}
return $ret;
} else {
$ret = '';
foreach ($this->libraries as $name => $library) {
$path = !empty($library['absPath'])? $library['absPath']: $this->defaultAbsPath;
if (DIRECTORY_SEPARATOR != substr($path, -1)) {
$path .= DIRECTORY_SEPARATOR;
}
if (false === ($file = @file_get_contents($path . $library['file']))) {
throw new HTML_QuickForm2_NotFoundException(
"File '{$library['file']}' for JS library '{$name}' not found at '{$path}'"
);
}
$ret .= ('' == $ret? '': "\n") . $file;
}
return $addScriptTags ? $this->wrapScript($ret) : $ret;
}
}
/**
* Sets ID of the form currently being processed
*
* All subsequent calls to addRule() and addElementJavascript() will store
* the scripts for that form
*
* @param string $formId
*/
public function setFormId($formId)
{
$this->formId = $formId;
$this->rules[$this->formId] = [];
$this->scripts[$this->formId] = [];
$this->forceValidator[$this->formId] = false;
}
/**
* Adds the Rule javascript to the list of current form Rules
*
* @param HTML_QuickForm2_Rule $rule Rule instance
* @param bool $triggers Whether rule code should contain
* "triggers" for live validation
*/
public function addRule(HTML_QuickForm2_Rule $rule, $triggers = false)
{
$this->rules[$this->formId][] = $rule->getJavascript($triggers);
}
/**
* Adds element's setup code to form's Javascript
*
* @param string $script
*/
public function addElementJavascript($script)
{
$this->scripts[$this->formId][] = $script;
}
/**
* Enables generating a validator for the current form even if no rules are present
*/
public function forceValidator()
{
$this->forceValidator[$this->formId] = true;
}
/**
* Returns per-form javascript (client-side validation and elements' setup)
*
* @param string $formId form ID, if empty returns code for all forms
* @param boolean $addScriptTags whether to enclose code in <script> tags
*
* @return string
*/
public function getFormJavascript($formId = null, $addScriptTags = true)
{
$js = $this->getValidator($formId, false);
$js .= ('' == $js ? '' : "\n") . $this->getSetupCode($formId, false);
return $addScriptTags ? $this->wrapScript($js) : $js;
}
/**
* Returns setup code for form elements
*
* @param string $formId form ID, if empty returns code for all forms
* @param bool $addScriptTags whether to enclose code in <script> tags
*
* @return string
*/
public function getSetupCode($formId = null, $addScriptTags = false)
{
$js = '';
foreach ($this->scripts as $id => $scripts) {
if ((null === $formId || $id == $formId) && !empty($scripts)) {
$js .= ('' == $js? '': "\n") . implode("\n", $scripts);
}
}
return $addScriptTags ? $this->wrapScript($js) : $js;
}
/**
* Returns client-side validation code
*
* @param string $formId form ID, if empty returns code for all forms
* @param bool $addScriptTags whether to enclose code in <script> tags
*
* @return string
*/
public function getValidator($formId = null, $addScriptTags = false)
{
$js = '';
foreach ($this->rules as $id => $rules) {
if ((null === $formId || $id == $formId)
&& (!empty($rules) || !empty($this->forceValidator[$id]))
) {
$js .= ('' == $js ? '' : "\n")
. "new qf.Validator(document.getElementById('{$id}'), [\n"
. implode(",\n", $rules) . "\n]);";
}
}
return $addScriptTags ? $this->wrapScript($js) : $js;
}
/**
* Wraps the given Javascript code in <script> tags
*
* @param string $js Javascript code
*
* @return string code wrapped in <script></script> tags,
* empty string if $js is empty
*/
protected function wrapScript($js)
{
if ('' != $js) {
$cr = HTML_Common2::getOption(HTML_Common2::OPTION_LINEBREAK);
$attributes = ' type="text/javascript"';
if (null !== ($nonce = HTML_Common2::getOption(HTML_QuickForm2_Node::OPTION_NONCE))) {
$attributes .= ' nonce="' . $nonce . '"';
}
$js = "<script{$attributes}>{$cr}//<![CDATA[{$cr}"
. $js . "{$cr}//]]>{$cr}</script>";
}
return $js;
}
/**
* Encodes a value for use as Javascript literal
*
* NB: unlike json_encode() we do not enforce UTF-8 charset here
*
* @param mixed $value
*
* @return string value as Javascript literal
*/
public static function encode($value)
{
if (is_null($value)) {
return 'null';
} elseif (is_bool($value)) {
return $value? 'true': 'false';
} elseif (is_int($value) || is_float($value)) {
return (string)$value;
} elseif (is_string($value)) {
return '"' . strtr($value, [
"\r" => '\r',
"\n" => '\n',
"\t" => '\t',
"'" => "\\'",
'"' => '\"',
'\\' => '\\\\'
]) . '"';
} elseif (is_array($value)) {
// associative array, encoding as JS object
if (count($value) && array_keys($value) !== range(0, count($value) - 1)) {
return '{' . implode(',', array_map(
['HTML_QuickForm2_JavascriptBuilder', 'encodeNameValue'],
array_keys($value), array_values($value)
)) . '}';
}
return '[' . implode(',', array_map(
['HTML_QuickForm2_JavascriptBuilder', 'encode'],
$value
)) . ']';
} elseif (is_object($value)) {
$vars = get_object_vars($value);
return '{' . implode(',', array_map(
['HTML_QuickForm2_JavascriptBuilder', 'encodeNameValue'],
array_keys($vars), array_values($vars)
)) . '}';
} else {
throw new HTML_QuickForm2_InvalidArgumentException(
'Cannot encode ' . gettype($value) . ' as Javascript value'
);
}
}
/**
* Callback for array_map used to generate name-value pairs
*
* @param mixed $name
* @param mixed $value
*
* @return string
*/
protected static function encodeNameValue($name, $value)
{
return self::encode((string)$name) . ':' . self::encode($value);
}
}
?>