| @@ -94,19 +94,62 @@ | ||
| 94 | 94 | $this->load_frontend_styles(); |
| 95 | 95 | $this->load_frontend_scripts(); |
| 96 | 96 | } |
| 97 | 97 | |
| 98 | + /** | |
| 99 | + * Flatten a decoded selection attribute into a plain list of values. | |
| 100 | + * | |
| 101 | + * Selection attributes are saved by the editor as `[{ value, label }]` | |
| 102 | + * objects, but a bare list of values — `[5, 7]` — is what REST clients and | |
| 103 | + * other programmatic writers naturally produce. Both shapes are accepted: | |
| 104 | + * an array element contributes its `$key`, a scalar element contributes | |
| 105 | + * itself, and elements that carry no value are dropped. | |
| 106 | + * | |
| 107 | + * @since 4.9.0 | |
| 108 | + * | |
| 109 | + * @param mixed $decoded Decoded attribute value. Anything that is not an array yields an empty list. | |
| 110 | + * @param string $key Key holding the value on object elements. Default 'value'. | |
| 111 | + * | |
| 112 | + * @return array Re-indexed list of values. | |
| 113 | + */ | |
| 114 | + public static function normalize_id_list( $decoded, $key = 'value' ) { | |
| 115 | + if ( ! is_array( $decoded ) ) { | |
| 116 | + return []; | |
| 117 | + } | |
| 118 | + | |
| 119 | + $_values = array_map( | |
| 120 | + function ( $item ) use ( $key ) { | |
| 121 | + return is_array( $item ) ? ( isset( $item[ $key ] ) ? $item[ $key ] : null ) : $item; | |
| 122 | + }, | |
| 123 | + $decoded | |
| 124 | + ); | |
| 125 | + | |
| 126 | + return array_values( | |
| 127 | + array_filter( | |
| 128 | + $_values, | |
| 129 | + function ( $value ) { | |
| 130 | + return null !== $value; | |
| 131 | + } | |
| 132 | + ) | |
| 133 | + ); | |
| 134 | + } | |
| 135 | + | |
| 136 | + /** | |
| 137 | + * Decode a JSON attribute string into a list of values. | |
| 138 | + * | |
| 139 | + * @since 4.9.0 Bare-value lists (`"[5]"`) are accepted alongside the | |
| 140 | + * editor's `[{ value, label }]` form, and no longer warn. | |
| 141 | + * | |
| 142 | + * @param mixed $data JSON encoded attribute value; non-strings yield an empty list. | |
| 143 | + * @param string $key Key holding the value on object elements. Default 'value'. | |
| 144 | + * | |
| 145 | + * @return array | |
| 146 | + */ | |
| 98 | 147 | public function string_to_array( $data = [], $key = 'value' ) { |
| 99 | 148 | $_return_val = []; |
| 100 | 149 | |
| 101 | 150 | if ( is_string( $data ) && ! empty( $data ) ) { |
| 102 | - $_return_val = json_decode( $data, true ); | |
| 103 | - $_return_val = array_map( | |
| 104 | - function ( $item ) use ( &$key ) { | |
| 105 | - return $item[ $key ]; | |
| 106 | - }, | |
| 107 | - $_return_val == null || empty( $_return_val ) ? [] : $_return_val | |
| 108 | - ); | |
| 151 | + $_return_val = self::normalize_id_list( json_decode( $data, true ), $key ); | |
| 109 | 152 | } |
| 110 | 153 | |
| 111 | 154 | return $_return_val; |
| 112 | 155 | } |