PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.3
Jetpack – WP Security, Backup, Speed, & Growth v16.3
16.3 16.3-beta 16.3-a.5 16.3-a.7 16.3-a.3 16.3-a.1 16.2 16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 All 508 releases
← All changes | modules/wordads/php/class-wordads-array-utils.php +71 -0 16.2-beta → 16.3 View file →
@@ -1,0 +1,71 @@
1 +<?php
2 +/**
3 + * A utility class that provides functionality for manipulating arrays.
4 + *
5 + * @package automattic/jetpack
6 + */
7 +
8 +if ( ! defined( 'ABSPATH' ) ) {
9 + exit( 0 );
10 +}
11 +
12 +/**
13 + * WordAds_Array_Utils Class.
14 + */
15 +final class WordAds_Array_Utils {
16 +
17 + /**
18 + * Converts a (potentially nested) array to a JavaScript object.
19 + *
20 + * Note: JS code strings should be prefixed with 'js:'.
21 + *
22 + * @param array $value The array to convert to a JavaScript object.
23 + * @param bool $in_list True if we are processing an inner list (non-associative array).
24 + *
25 + * @return string String representation of the JavaScript object
26 + */
27 + public static function array_to_js_object( array $value, bool $in_list = false ): string {
28 + $properties = array();
29 +
30 + foreach ( $value as $k => $v ) {
31 + // Don't set property key for values from non-associative array.
32 + $property_key = $in_list ? '' : "'$k': ";
33 +
34 + if ( is_array( $v ) ) {
35 + // Check for empty array.
36 + if ( array() === $v ) {
37 + $properties[] = "'$k': []";
38 + continue;
39 + }
40 +
41 + // Check if this is a list and not an associative array.
42 + if ( array_keys( $v ) === range( 0, count( $v ) - 1 ) ) {
43 + // Apply recursively.
44 + $properties[] = $property_key . '[ ' . self::array_to_js_object( $v, true ) . ' ]';
45 + } else {
46 + // Apply recursively.
47 + $properties[] = $property_key . self::array_to_js_object( $v );
48 + }
49 + } elseif ( is_string( $v ) && strpos( $v, 'js:' ) === 0 ) {
50 + // JS code. Strip the 'js:' prefix.
51 + $properties[] = $property_key . substr( $v, 3 );
52 + } elseif ( is_string( $v ) ) {
53 + $properties[] = $property_key . "'" . addcslashes( $v, "'" ) . "'";
54 + } elseif ( is_bool( $v ) ) {
55 + $properties[] = $property_key . ( $v ? 'true' : 'false' );
56 + } elseif ( $v === null ) {
57 + $properties[] = $property_key . 'null';
58 + } else {
59 + $properties[] = $property_key . $v;
60 + }
61 + }
62 +
63 + $output = implode( ', ', $properties );
64 +
65 + if ( ! $in_list ) {
66 + $output = '{ ' . $output . ' }';
67 + }
68 +
69 + return $output;
70 + }
71 +}