Test Failed
Push — main ( 86f2f1...c3aa2d )
by Jean-Christophe
01:46
created

JavascriptUtils::wrapScript()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
namespace PHPMV\js;
3
4
/**
5
 * Javascript utilities.
6
 * PHPMV\js$JavascriptUtils
7
 * This class is part of php-ui-common
8
 *
9
 * @author jc
10
 * @version 1.0.0
11
 *
12
 */
13
class JavascriptUtils {
14
15
	/**
16
	 * Returns a JSON string from an object.
17
	 *
18
	 * @param mixed $object
19
	 * @return string
20
	 */
21
	public static function toJSON($object): string {
22
		if (\is_object($object)) {
23
			if (\method_exists($object, 'toArray')) {
24
				$object = $object->toArray();
25
			} else {
26
				$object = (array) $object;
27
			}
28
		}
29
		return \json_encode($object, \JSON_PRETTY_PRINT | \JSON_NUMERIC_CHECK);
30
	}
31
32
	/**
33
	 * Add script tags to a javascript code.
34
	 *
35
	 * @param string $script
36
	 * @return string
37
	 */
38
	public static function wrapScript(string $script): string {
39
		if ($script == null) {
40
			return '';
41
		}
42
		if (\substr($script, 0, \strlen('<script>')) !== '<script>') {
43
			$script = "<script>$script</script>";
44
		}
45
		return $script;
46
	}
47
}
48
49