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

JsUtils   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 91.67%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 12
c 2
b 0
f 0
dl 0
loc 33
ccs 11
cts 12
cp 0.9167
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A objectToJSON() 0 9 3
A wrapScript() 0 8 3
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