Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
WordAds_Array_Utils
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
182
0.00% covered (danger)
0.00%
0 / 1
 array_to_js_object
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
182
1<?php
2/**
3 * A utility class that provides functionality for manipulating arrays.
4 *
5 * @package automattic/jetpack
6 */
7
8if ( ! defined( 'ABSPATH' ) ) {
9    exit( 0 );
10}
11
12/**
13 * WordAds_Array_Utils Class.
14 */
15final 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}