Data.php
68 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Handles adding script data to the page in cases where localizing a |
| 4 | * specific script is not suitable. |
| 5 | * |
| 6 | * Should generally be accessed via tribe( 'tribe.asset.script-data' ) |
| 7 | * rather than via direct instantiation. |
| 8 | */ |
| 9 | class Tribe__Asset__Data { |
| 10 | /** |
| 11 | * Container for any JS data objects that should be added to the page. |
| 12 | * |
| 13 | * @var array |
| 14 | */ |
| 15 | protected $objects = []; |
| 16 | |
| 17 | /** |
| 18 | * Hooks up the method used to actually render the JSON data. |
| 19 | */ |
| 20 | public function hook() { |
| 21 | if ( is_admin() ) { |
| 22 | add_action( 'admin_footer', [ $this, 'render_json' ] ); |
| 23 | add_action( 'customize_controls_print_footer_scripts', [ $this, 'render_json' ] ); |
| 24 | } else { |
| 25 | add_action( 'wp_footer', [ $this, 'render_json' ] ); |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * Adds the provided data to the list of objects that should be available |
| 31 | * to other scripts. |
| 32 | * |
| 33 | * @param string $object_name Object name. |
| 34 | * @param array $data Object data. |
| 35 | */ |
| 36 | public function add( $object_name, $data ) { |
| 37 | /** |
| 38 | * Allow plugins to filter data for a specific object. |
| 39 | * |
| 40 | * @since 4.8.4 |
| 41 | * |
| 42 | * @param array $data Object data. |
| 43 | * @param string $object_name Object name. |
| 44 | */ |
| 45 | $data = apply_filters( "tribe_asset_data_add_object_{$object_name}", $data, $object_name ); |
| 46 | |
| 47 | $this->objects[ $object_name ] = $data; |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Outputs the |
| 52 | * @internal |
| 53 | */ |
| 54 | public function render_json() { |
| 55 | if ( empty( $this->objects ) ) { |
| 56 | return; |
| 57 | } |
| 58 | |
| 59 | echo '<script> /* <![CDATA[ */'; |
| 60 | |
| 61 | foreach ( $this->objects as $object_name => $data ) { |
| 62 | echo 'var ' . esc_html( $object_name ) . ' = ' . wp_json_encode( $data ) . ';'; |
| 63 | } |
| 64 | |
| 65 | echo '/* ]]> */ </script>'; |
| 66 | } |
| 67 | } |
| 68 |