PluginProbe
Gutenberg / 16.6.0
Gutenberg v16.6.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-directive-context.php

class-wp-directive-context.php in Gutenberg 16.6.0, at lib/experimental/interactivity-api/class-wp-directive-context.php

82 lines 1.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Context data implementation.
4 *
5 * @package Gutenberg
6 * @subpackage Interactivity API
7 */
8
9 if ( class_exists( 'WP_Directive_Context' ) ) {
10 return;
11 }
12
13 /**
14 * This is a data structure to hold the current context.
15 *
16 * Whenever encountering a `data-wp-context` directive, we need to update
17 * the context with the data found in that directive. Conversely,
18 * when "leaving" that context (by encountering a closing tag), we
19 * need to reset the context to its previous state. This means that
20 * we actually need sort of a stack to keep track of all nested contexts.
21 *
22 * Example:
23 *
24 * <div data-wp-context='{ "foo": 123 }'>
25 * <!-- foo should be 123 here. -->
26 * <div data-wp-context='{ "foo": 456 }'>
27 * <!-- foo should be 456 here. -->
28 * </div>
29 * <!-- foo should be reset to 123 here. -->
30 * </div>
31 */
32 class WP_Directive_Context {
33 /**
34 * The stack used to store contexts internally.
35 *
36 * @var array An array of contexts.
37 */
38 protected $stack = array( array() );
39
40 /**
41 * Constructor.
42 *
43 * Accepts a context as an argument to initialize this with.
44 *
45 * @param array $context A context.
46 */
47 function __construct( $context = array() ) {
48 $this->set_context( $context );
49 }
50
51 /**
52 * Return the current context.
53 *
54 * @return array The current context.
55 */
56 public function get_context() {
57 return end( $this->stack );
58 }
59
60 /**
61 * Set the current context.
62 *
63 * @param array $context The context to be set.
64 *
65 * @return void
66 */
67 public function set_context( $context ) {
68 if ( $context ) {
69 array_push( $this->stack, array_replace_recursive( $this->get_context(), $context ) );
70 }
71 }
72
73 /**
74 * Reset the context to its previous state.
75 *
76 * @return void
77 */
78 public function rewind_context() {
79 array_pop( $this->stack );
80 }
81 }
82