Test Failed
Push — main ( 8d2cbe...fc198a )
by Jean-Christophe
02:12 queued 11s
created

JsUtils::objectToJSON()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 7
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 object $object
19
	 * @return string
20
	 */
21
	public static function objectToJSON(object $object): string {
22
		if (\method_exists($object, 'toArray')) {
23
			$array = $object->toArray();
24
		} else {
25
			$array = (array) $object;
26
		}
27
		return \json_encode($array, \JSON_PRETTY_PRINT | \JSON_NUMERIC_CHECK);
28
	}
29
30
	/**
31
	 * Add script tags to a javascript code.
32
	 *
33
	 * @param string $script
34
	 * @return string
35
	 */
36
	public static function wrapScript(string $script): string {
37
		if ($script == null) {
38
			return "";
39
		}
40
		if (\substr($script, 0, strlen("<script>")) === "<script>") {
41
			$script = "<script>$script</script>";
0 ignored issues
show
Unused Code introduced by
The assignment to $script is dead and can be removed.
Loading history...
42
		}
43
		return script;
0 ignored issues
show
Bug introduced by
The constant PHPMV\js\script was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
44
	}
45
}
46
47