| 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 |
if ( class_exists( 'WP_Interactivity_Store' ) ) { |
| 13 |
return; |
| 14 |
} |
| 15 |
|
| 16 |
/** |
| 17 |
* Manages the initial state of the Interactivity API store in the server and |
| 18 |
* its serialization so it can be restored in the browser upon hydration. |
| 19 |
* |
| 20 |
* It's a private class, exposed by other functions, like `wp_store`. |
| 21 |
* |
| 22 |
* @access private |
| 23 |
*/ |
| 24 |
class WP_Interactivity_Store { |
| 25 |
/** |
| 26 |
* Store. |
| 27 |
* |
| 28 |
* @var array |
| 29 |
*/ |
| 30 |
private static $store = array(); |
| 31 |
|
| 32 |
/** |
| 33 |
* Get store data. |
| 34 |
* |
| 35 |
* @return array |
| 36 |
*/ |
| 37 |
public static function get_data() { |
| 38 |
return self::$store; |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Merge data. |
| 43 |
* |
| 44 |
* @param array $data The data that will be merged with the existing store. |
| 45 |
*/ |
| 46 |
public static function merge_data( $data ) { |
| 47 |
self::$store = array_replace_recursive( self::$store, $data ); |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Reset the store data. |
| 52 |
*/ |
| 53 |
public static function reset() { |
| 54 |
self::$store = array(); |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Render the store data. |
| 59 |
*/ |
| 60 |
public static function render() { |
| 61 |
if ( empty( self::$store ) ) { |
| 62 |
return; |
| 63 |
} |
| 64 |
echo sprintf( |
| 65 |
'<script id="wp-interactivity-initial-state" type="application/json">%s</script>', |
| 66 |
wp_json_encode( self::$store, JSON_HEX_TAG | JSON_HEX_AMP ) |
| 67 |
); |
| 68 |
} |
| 69 |
} |
| 70 |
|