Passed
Push — main ( 280b4e...86f2f1 )
by Jean-Christophe
01:49
created

JsUtils::wrapScript()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 8
ccs 5
cts 6
cp 0.8333
crap 3.0416
rs 10
1
<?php
2
namespace PHPMV\js;
3
4
/**
5
 * Javascript utilities.
6
 * PHPMV\js$JsUtils
7
 * This class is part of php-ui-common
8
 *
9
 * @author jc
10
 * @version 1.0.0
11
 *
12
 */
13
class JsUtils {
14
15
	/**
16
	 * Returns a JSON string from an object.
17
	 *
18
	 * @param mixed $object
19
	 * @return string
20
	 */
21 1
	public static function objectToJSON($object): string {
22 1
		if (\is_object($object)) {
23 1
			if (\method_exists($object, 'toArray')) {
24 1
				$object = $object->toArray();
25
			} else {
26 1
				$object = (array) $object;
27
			}
28
		}
29 1
		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 1
	public static function wrapScript(string $script): string {
39 1
		if ($script == null) {
40
			return "";
41
		}
42 1
		if (\substr($script, 0, strlen("<script>")) !== "<script>") {
43 1
			$script = "<script>$script</script>";
44
		}
45 1
		return $script;
46
	}
47
}
48
49