| 1 |
<?php |
| 2 |
/** |
| 3 |
* WP_Interactivity_Store class |
| 4 |
* |
| 5 |
* Manages the initial state of the Interactivity API store in the server and |
| 6 |
* its serialization so it can be restored in the browser upon hydration. |
| 7 |
* |
| 8 |
* @package Gutenberg |
| 9 |
* @subpackage Interactivity API |
| 10 |
*/ |
| 11 |
|
| 12 |
/** |
| 13 |
* Manages the initial state of the Interactivity API store in the server and |
| 14 |
* its serialization so it can be restored in the browser upon hydration. |
| 15 |
* |
| 16 |
* It's a private class, exposed by other functions, like `wp_store`. |
| 17 |
* |
| 18 |
* @access private |
| 19 |
*/ |
| 20 |
class WP_Interactivity_Store { |
| 21 |
/** |
| 22 |
* Store. |
| 23 |
* |
| 24 |
* @var array |
| 25 |
*/ |
| 26 |
private static $store = array(); |
| 27 |
|
| 28 |
/** |
| 29 |
* Get store data. |
| 30 |
* |
| 31 |
* @return array |
| 32 |
*/ |
| 33 |
static function get_data() { |
| 34 |
return self::$store; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Merge data. |
| 39 |
* |
| 40 |
* @param array $data The data that will be merged with the existing store. |
| 41 |
*/ |
| 42 |
static function merge_data( $data ) { |
| 43 |
self::$store = array_replace_recursive( self::$store, $data ); |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Serialize store data to JSON. |
| 48 |
* |
| 49 |
* @return string|false Serialized JSON data. |
| 50 |
*/ |
| 51 |
static function serialize() { |
| 52 |
// TODO: Escape? |
| 53 |
return wp_json_encode( self::$store ); |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* Reset the store data. |
| 58 |
*/ |
| 59 |
static function reset() { |
| 60 |
self::$store = array(); |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Render the store data. |
| 65 |
*/ |
| 66 |
static function render() { |
| 67 |
if ( empty( self::$store ) ) { |
| 68 |
return; |
| 69 |
} |
| 70 |
$store = self::serialize(); |
| 71 |
echo "<script id=\"wp-interactivity-store-data\" type=\"application/json\">$store</script>"; |
| 72 |
} |
| 73 |
} |
| 74 |
|