= self::MAX_PATHS ) { break; } } return array_keys( $out ); } /** * The paths to preload on a screen, after the filter. * * @param string $screen Screen slug. * @return string[] */ public static function paths( string $screen ): array { /** * Filter the REST paths preloaded with a SubtleForms admin screen. * * Each path is a GET route of this plugin with the exact query string * the screen's script will request, for example * `/subtleforms/v1/analytics/summary?days=30`. Paths outside * `/subtleforms/v1/` are ignored. The answer is computed with the * current user, so a route the user may not read is left out. * * @param string[] $paths REST paths. * @param string $screen Screen slug, for example `subtleforms-forms`. * @since 2.7.4 */ $paths = apply_filters( 'subtleforms/admin/preload_paths', self::defaultPaths( $screen ), $screen ); return self::acceptable( $paths ); } /** * Preloaded answers for a screen, keyed by path, in the shape * `apiFetch.createPreloadingMiddleware()` takes: `{ body, headers }`. * * @param string $screen Screen slug. * @return array> */ public static function collect( string $screen ): array { if ( '' === $screen || ! is_user_logged_in() || ! function_exists( 'rest_preload_api_request' ) ) { return array(); } $caps = new \SubtleForms\Support\Capabilities(); if ( ! current_user_can( $caps->manage_cap() ) ) { return array(); } $paths = self::paths( $screen ); if ( array() === $paths ) { return array(); } // The routes of this plugin ask for the REST nonce the browser would send. // Give each preloaded request the nonce of the current user, as the // browser's own request would carry, and take the filter off again. $nonce = wp_create_nonce( 'wp_rest' ); $attach = static function ( $result, $server, $request ) use ( $nonce ) { if ( $request instanceof \WP_REST_Request && '' === (string) $request->get_header( 'X-WP-Nonce' ) ) { $request->set_header( 'X-WP-Nonce', $nonce ); } return $result; }; add_filter( 'rest_pre_dispatch', $attach, 0, 3 ); $preloaded = array_reduce( $paths, 'rest_preload_api_request', array() ); remove_filter( 'rest_pre_dispatch', $attach, 0 ); return is_array( $preloaded ) ? $preloaded : array(); } }