|
6 | 6 | * Request helper class.
|
7 | 7 | */
|
8 | 8 | final class Request {
|
| 9 | + /** |
| 10 | + * Check if a REST namespace should be loaded. Useful to maintain site performance even when lots of REST namespaces are registered. |
| 11 | + * |
| 12 | + * @since 9.2.0. |
| 13 | + * |
| 14 | + * @param string $space The namespace to check. |
| 15 | + * @param string $route (Optional) The REST route being checked. |
| 16 | + * @param array<string> $known Known namespaces that we know are safe to not load if the request is not for them. |
| 17 | + * |
| 18 | + * @return bool True if the namespace should be loaded, false otherwise. |
| 19 | + */ |
| 20 | + public static function should_load_rest_ns( string $space, ?string $route = null, array $known = array() ): bool { |
| 21 | + $route ??= $GLOBALS['wp']->query_vars['rest_route'] ?? false; |
| 22 | + |
| 23 | + if ( ! $route ) { |
| 24 | + return true; |
| 25 | + } |
| 26 | + |
| 27 | + $route = \trailingslashit( \ltrim( $route, '/' ) ); |
| 28 | + $space = \trailingslashit( $space ); |
| 29 | + |
| 30 | + /** |
| 31 | + * Known namespaces that we know are safe to not load if the request is not for them. |
| 32 | + * Namespaces not in this namespace should always be loaded, because we don't know if they won't be making another internal REST request to an unloaded namespace. |
| 33 | + * |
| 34 | + * @param array<string> $known_ns Known namespaces that we know are safe to not load if the request is not for them. |
| 35 | + * @param string $space The namespace to check. |
| 36 | + * @param string $route The REST route being checked. |
| 37 | + * @return array<string> |
| 38 | + * |
| 39 | + * @since 1.16.0 |
| 40 | + */ |
| 41 | + $known = \apply_filters( 'xwp_known_rest_namespaces', $known, $space, $route ); |
| 42 | + |
| 43 | + if ( ! \array_reduce( $known, static fn( $c, $r ) => $c || \str_starts_with( $route, $r ), false ) ) { |
| 44 | + return true; |
| 45 | + } |
| 46 | + |
| 47 | + $load = \str_starts_with( $route, $space ); |
| 48 | + |
| 49 | + /** |
| 50 | + * Filters whether a namespace should be loaded. |
| 51 | + * |
| 52 | + * @param bool $load True if the namespace should be loaded, false otherwise. |
| 53 | + * @param string $space The namespace to check. |
| 54 | + * @param string $route The REST route being checked. |
| 55 | + * @param array $known Known namespaces that we know are safe to not load if the request is not for them. |
| 56 | + * @return bool |
| 57 | + * |
| 58 | + * @since 1.16.0 |
| 59 | + */ |
| 60 | + return \apply_filters( 'xwp_rest_can_load_namespace', $load, $space, $route, $known ); |
| 61 | + } |
| 62 | + |
9 | 63 | /**
|
10 | 64 | * Clean input data.
|
11 | 65 | *
|
|
0 commit comments