Passed
Pull Request — master (#1005)
by Fabio
28:04 queued 18:59
created

TJavaScript::renderScriptFooter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
1
<?php
2
3
/**
4
 * TJavaScript class file
5
 *
6
 * @author Wei Zhuo<weizhuo[at]gmail[dot]com>
7
 * @link https://github.com/pradosoft/prado
8
 * @license https://github.com/pradosoft/prado/blob/master/LICENSE
9
 */
10
11
namespace Prado\Web\Javascripts;
12
13
use Prado\Web\THttpUtility;
14
use Prado\Prado;
15
16
/**
17
 * TJavaScript class.
18
 *
19
 * TJavaScript is a utility class containing commonly-used javascript-related
20
 * functions.
21
 *
22
 * @author Wei Zhuo<weizhuo[at]gmail[dot]com>
23
 * @since 3.0
24
 */
25
class TJavaScript
26
{
27
	/**
28
	 * Renders javascript header block
29
	 * @return string rendering result
30
	 */
31
	public static function renderScriptHeader()
32
	{
33
		return "<script>\n/*<![CDATA[*/\n";
34
	}
35
36
	/**
37
	 * Renders javascript footer block
38
	 * @return string rendering result
39
	 */
40
	public static function renderScriptFooter()
41
	{
42
		return "\n/*]]>*/\n</script>\n";
43
	}
44
45
	/**
46
	 * Renders a list of javascript files
47
	 * @param array $files URLs to the javascript files
48
	 * @return string rendering result
49
	 */
50
	public static function renderScriptFiles($files)
51
	{
52
		$str = '';
53
		foreach ($files as $file) {
54
			$str .= self::renderScriptFile($file);
55
		}
56
		return $str;
57
	}
58
59
	/**
60
	 * Renders a javascript file
61
	 * @param \Prado\Web\Javascripts\TJavaScriptAsset|string $asset URL to the javascript file or TJavaScriptAsset
62
	 * @return string rendering result
63
	 */
64
	public static function renderScriptFile($asset)
65
	{
66
		if (is_object($asset) && ($asset instanceof TJavaScriptAsset)) {
67
			return $asset->__toString() . "\n";
68
		}
69
		return '<script src="' . THttpUtility::htmlEncode($asset) . "\"></script>\n";
70
	}
71
72
	/**
73
	 * Renders a list of javascript blocks
74
	 * @param array $scripts javascript blocks
75
	 * @return string rendering result
76
	 */
77
	public static function renderScriptBlocks($scripts)
78
	{
79
		if (count($scripts)) {
80
			return self::renderScriptHeader() . implode("\n", $scripts) . self::renderScriptFooter();
81
		} else {
82
			return '';
83
		}
84
	}
85
86
	/**
87
	 * Renders a list of javascript code
88
	 * @param array $scripts javascript blocks
89
	 * @return string rendering result
90
	 */
91
	public static function renderScriptBlocksCallback($scripts)
92
	{
93
		if (count($scripts)) {
94
			return implode("\n", $scripts) . "\n";
95
		} else {
96
			return '';
97
		}
98
	}
99
100
	/**
101
	 * Renders javascript block
102
	 * @param string $script javascript block
103
	 * @return string rendering result
104
	 */
105
	public static function renderScriptBlock($script)
106
	{
107
		return self::renderScriptHeader() . $script . self::renderScriptFooter();
108
	}
109
110
	/**
111
	 * Quotes a javascript string.
112
	 * After processing, the string is safely enclosed within a pair of
113
	 * quotation marks and can serve as a javascript string.
114
	 * @param string $js string to be quoted
115
	 * @return string the quoted string
116
	 */
117
	public static function quoteString($js)
118
	{
119
		return self::jsonEncode($js, JSON_HEX_QUOT | JSON_HEX_APOS | JSON_HEX_TAG);
120
	}
121 92
122
	/**
123 92
	 * @param mixed $js
124
	 * @return TJavaScriptLiteral Marks a string as a javascript function. Once marke, the string is considered as a
125
	 * raw javascript function that is not supposed to be encoded by {@see encode}
126
	 */
127
	public static function quoteJsLiteral($js)
128
	{
129
		if ($js instanceof TJavaScriptLiteral) {
130
			return $js;
131
		} else {
132
			return new TJavaScriptLiteral($js);
133
		}
134
	}
135
136
	/**
137
	 * @param mixed $js
138
	 * @return bool true if the parameter is marked as a javascript function, i.e. if it's considered as a
139
	 * raw javascript function that is not supposed to be encoded by {@see encode}
140
	 */
141
	public static function isJsLiteral($js)
142
	{
143
		return ($js instanceof TJavaScriptLiteral);
144
	}
145
146
	/**
147
	 * Encodes a PHP variable into javascript representation.
148
	 *
149
	 * Example:
150
	 * ```php
151
	 * $options['onLoading'] = "doit";
152
	 * $options['onComplete'] = "more";
153
	 * echo TJavaScript::encode($options);
154
	 * //expects the following javascript code
155
	 * // {'onLoading':'doit','onComplete':'more'}
156
	 * ```
157
	 *
158
	 * For higher complexity data structures use {@see jsonEncode} and {@see jsonDecode}
159
	 * to serialize and unserialize.
160
	 *
161
	 * @param mixed $value PHP variable to be encoded
162
	 * @param bool $toMap whether the output is a map or a list.
163
	 * @since 3.1.5
164
	 * @param bool $encodeEmptyStrings wether to encode empty strings too. Default to false for BC.
165
	 * @return string the encoded string
166
	 */
167
	public static function encode($value, $toMap = true, $encodeEmptyStrings = false)
168
	{
169
		if (is_string($value)) {
170
			return self::quoteString($value);
171
		} elseif (is_bool($value)) {
172
			return $value ? 'true' : 'false';
173
		} elseif (is_array($value)) {
174
			$results = '';
175
			if (($n = count($value)) > 0 && array_keys($value) !== range(0, $n - 1)) {
176
				foreach ($value as $k => $v) {
177
					if ($v !== '' || $encodeEmptyStrings) {
178
						if ($results !== '') {
179
							$results .= ',';
180
						}
181
						$results .= "'$k':" . self::encode($v, $toMap, $encodeEmptyStrings);
182
					}
183
				}
184
				return '{' . $results . '}';
185
			} else {
186
				foreach ($value as $v) {
187
					if ($v !== '' || $encodeEmptyStrings) {
188
						if ($results !== '') {
189
							$results .= ',';
190
						}
191
						$results .= self::encode($v, $toMap, $encodeEmptyStrings);
192
					}
193
				}
194
				return '[' . $results . ']';
195
			}
196
		} elseif (is_int($value)) {
197
			return "$value";
198
		} elseif (is_float($value)) {
199
			switch ($value) {
200
				case -INF:
201
					return 'Number.NEGATIVE_INFINITY';
202
					break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
203
				case INF:
204
					return 'Number.POSITIVE_INFINITY';
205
					break;
206
				default:
207
					$locale = localeConv();
208
					if ($locale['decimal_point'] == '.') {
209
						return "$value";
210
					} else {
211
						return str_replace($locale['decimal_point'], '.', "$value");
212
					}
213
					break;
214
			}
215
		} elseif (is_object($value)) {
216
			if ($value instanceof TJavaScriptLiteral) {
217
				return $value->toJavaScriptLiteral();
218
			} else {
219
				return self::encode(get_object_vars($value), $toMap);
220
			}
221
		} elseif ($value === null) {
222
			return 'null';
223
		} else {
224
			return '';
225
		}
226
	}
227
	/**
228
	 * Encodes a PHP variable into javascript string.
229
	 * This method invokes json_encode to perform the encoding.
230
	 * @param mixed $value variable to be encoded
231
	 * @param mixed $options
232
	 * @return string encoded string
233
	 */
234
	public static function jsonEncode($value, $options = 0)
235
	{
236
		if (($g = Prado::getApplication()->getGlobalization(false)) !== null &&
237
			strtoupper($enc = $g->getCharset()) != 'UTF-8') {
238
			self::convertToUtf8($value, $enc);
239
		}
240
241
		return json_encode($value, $options | JSON_THROW_ON_ERROR);
242
	}
243
244
	/**
245
	 * Encodes an string or the content of an array to UTF8
246
	 * @param array|mixed|string $value
247
	 * @param string $sourceEncoding
248
	 */
249
	private static function convertToUtf8(&$value, $sourceEncoding)
250
	{
251
		if (is_string($value)) {
252
			$value = iconv($sourceEncoding, 'UTF-8', $value);
253
		} elseif (is_array($value)) {
254
			foreach ($value as &$element) {
255
				self::convertToUtf8($element, $sourceEncoding);
256
			}
257
		}
258
	}
259
260
	/**
261
	 * Decodes a javascript string into PHP variable.
262
	 * This method invokes json_decode to perform the decoding.
263
	 * @param string $value string to be decoded
264
	 * @param bool $assoc whether to convert returned objects to associative arrays
265
	 * @param int $depth recursion depth
266
	 * @return mixed decoded variable
267
	 */
268
	public static function jsonDecode($value, $assoc = false, $depth = 512)
269
	{
270
		return json_decode($value, $assoc, $depth, JSON_THROW_ON_ERROR);
271
	}
272
273
	/**
274
	 * Minimize the size of a javascript script.
275
	 * This method is based on Douglas Crockford's JSMin.
276
	 * @param string $code code that you want to minimzie
277
	 * @return string minimized version of the code
278
	 */
279
	public static function JSMin($code)
280
	{
281
		return \JSMin\JSMin::minify($code);
282
	}
283
}
284