PluginProbe
Gutenberg / 17.5.0
Gutenberg v17.5.0
24.0.0 23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 All 403 releases
gutenberg / lib / experimental / interactivity-api / class-wp-interactivity-initial-state.php

class-wp-interactivity-initial-state.php in Gutenberg 17.5.0, at lib/experimental/interactivity-api/class-wp-interactivity-initial-state.php

83 lines 1.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * WP_Interactivity_Initial_State class
4 *
5 * @package Gutenberg
6 * @subpackage Interactivity API
7 */
8
9 if ( class_exists( 'WP_Interactivity_Initial_State' ) ) {
10 return;
11 }
12
13 /**
14 * Manages the initial state of the Interactivity API store in the server and
15 * its serialization so it can be restored in the browser upon hydration.
16 *
17 * @package Gutenberg
18 * @subpackage Interactivity API
19 */
20 class WP_Interactivity_Initial_State {
21 /**
22 * Map of initial state by namespace.
23 *
24 * @var array
25 */
26 private static $initial_state = array();
27
28 /**
29 * Get state from a given namespace.
30 *
31 * @param string $store_ns Namespace.
32 *
33 * @return array The requested state.
34 */
35 public static function get_state( $store_ns ) {
36 return self::$initial_state[ $store_ns ] ?? array();
37 }
38
39 /**
40 * Merge data into the state with the given namespace.
41 *
42 * @param string $store_ns Namespace.
43 * @param array $data State to merge.
44 *
45 * @return void
46 */
47 public static function merge_state( $store_ns, $data ) {
48 self::$initial_state[ $store_ns ] = array_replace_recursive(
49 self::get_state( $store_ns ),
50 $data
51 );
52 }
53
54 /**
55 * Get store data.
56 *
57 * @return array
58 */
59 public static function get_data() {
60 return self::$initial_state;
61 }
62
63 /**
64 * Reset the initial state.
65 */
66 public static function reset() {
67 self::$initial_state = array();
68 }
69
70 /**
71 * Render the initial state.
72 */
73 public static function render() {
74 if ( empty( self::$initial_state ) ) {
75 return;
76 }
77 echo sprintf(
78 '<script id="wp-interactivity-initial-state" type="application/json">%s</script>',
79 wp_json_encode( self::$initial_state, JSON_HEX_TAG | JSON_HEX_AMP )
80 );
81 }
82 }
83