| 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 |
public 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 |
array_push( |
| 69 |
$this->stack, |
| 70 |
array_replace_recursive( $this->get_context(), $context ) |
| 71 |
); |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* Reset the context to its previous state. |
| 76 |
* |
| 77 |
* @return void |
| 78 |
*/ |
| 79 |
public function rewind_context() { |
| 80 |
array_pop( $this->stack ); |
| 81 |
} |
| 82 |
} |
| 83 |
|