Test Failed
Push — main ( e4bdb4...9a2b38 )
by Jean-Christophe
01:50
created

JavascriptUtils::arrayToJsObject()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 6.1666

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 8
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 11
ccs 5
cts 6
cp 0.8333
crap 6.1666
rs 9.2222
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 1
	public static function toJSON($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
	 * Return a javascript object from a php associative array.
34
	 *
35
	 * @param array $array
36
	 * @return string
37
	 */
38 1
	public static function arrayToJsObject(array $array): string {
39 1
		$res = [];
40
		foreach ($array as $k => $v) {
41
			if (\is_object($v) || \is_array($v)) {
42 1
				$v = self::toJSON($v);
43 1
			} elseif (\is_bool($v)) {
44
				$v = ($v) ? 'true' : 'false';
45 1
			}
46
			$res[] = "$k: $v";
47
		}
48
		return '{' . \implode(',', $res) . '}';
49
	}
50
51
	/**
52
	 * Add script tags to a javascript code.
53
	 *
54
	 * @param string $script
55
	 * @return string
56
	 */
57
	public static function wrapScript(string $script): string {
58
		if ($script == null) {
59
			return '';
60
		}
61
		if (\substr($script, 0, \strlen('<script>')) !== '<script>') {
62
			$script = "<script>$script</script>";
63
		}
64
		return $script;
65
	}
66
}
67
68