for enqueuing asset data via the WP api. * * Note: while this is hooked into print/admin_print_scripts, it still only * happens if the script attached to `wc-settings` handle is enqueued. This * is done to allow for any potentially expensive data generation to only * happen for routes that need it. */ public function enqueue_asset_data() { if ( wp_script_is( $this->handle, 'enqueued' ) ) { $this->initialize_core_data(); $this->execute_lazy_data(); $data = rawurlencode( wp_json_encode( $this->data ) ); $wc_settings_script = "var wcSettings = JSON.parse( decodeURIComponent( '" . esc_js( $data ) . "' ) );"; $preloaded_api_requests_script = ''; if ( count( $this->preloaded_api_requests ) > 0 ) { $preloaded_api_requests = rawurlencode( wp_json_encode( $this->preloaded_api_requests ) ); $preloaded_api_requests_script = "wp.apiFetch.use( wp.apiFetch.createPreloadingMiddleware( JSON.parse( decodeURIComponent( '" . esc_js( $preloaded_api_requests ) . "' ) ) ) );"; } wp_add_inline_script( $this->handle, $wc_settings_script . $preloaded_api_requests_script, 'before' ); } } /** * See self::add() for docs. * * @param string $key Key for the data. * @param mixed $data Value for the data. */ protected function add_data( $key, $data ) { if ( ! is_string( $key ) ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error trigger_error( esc_html__( 'Key for the data being registered must be a string', 'woocommerce' ), E_USER_WARNING ); return; } if ( $this->exists( $key ) ) { return; } if ( isset( $this->data[ $key ] ) ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error trigger_error( esc_html__( 'Overriding existing data with an already registered key is not allowed', 'woocommerce' ), E_USER_WARNING ); return; } if ( \is_callable( $data ) ) { $this->lazy_data[ $key ] = $data; return; } $this->data[ $key ] = $data; } /** * Exposes whether the current site is in debug mode or not. * * @return boolean True means the site is in debug mode. */ protected function debug() { return defined( 'WP_DEBUG' ) && WP_DEBUG; } }