| | 2015 | /** |
| | 2016 | * @ticket 39473 |
| | 2017 | */ |
| | 2018 | public function test_get_routes_caches_result() { |
| | 2019 | $filter_count = 0; |
| | 2020 | $counting_filter = static function ( $endpoints ) use ( &$filter_count ) { |
| | 2021 | ++$filter_count; |
| | 2022 | return $endpoints; |
| | 2023 | }; |
| | 2024 | |
| | 2025 | add_filter( 'rest_endpoints', $counting_filter ); |
| | 2026 | |
| | 2027 | $server = rest_get_server(); |
| | 2028 | $server->get_routes(); |
| | 2029 | $server->get_routes(); |
| | 2030 | $server->get_routes(); |
| | 2031 | |
| | 2032 | remove_filter( 'rest_endpoints', $counting_filter ); |
| | 2033 | |
| | 2034 | $this->assertSame( 1, $filter_count, 'The rest_endpoints filter should only fire once when get_routes() is called multiple times.' ); |
| | 2035 | } |
| | 2036 | |
| | 2037 | /** |
| | 2038 | * @ticket 39473 |
| | 2039 | */ |
| | 2040 | public function test_get_routes_cache_is_keyed_by_namespace() { |
| | 2041 | $server = rest_get_server(); |
| | 2042 | |
| | 2043 | $all_routes = $server->get_routes(); |
| | 2044 | $namespaced_routes = $server->get_routes( 'oembed/1.0' ); |
| | 2045 | |
| | 2046 | $this->assertNotEquals( $all_routes, $namespaced_routes, 'Cached routes for different namespaces should differ.' ); |
| | 2047 | |
| | 2048 | foreach ( $namespaced_routes as $route => $handlers ) { |
| | 2049 | $this->assertStringStartsWith( '/oembed/1.0', $route ); |
| | 2050 | } |
| | 2051 | } |
| | 2052 | |
| | 2053 | /** |
| | 2054 | * @ticket 39473 |
| | 2055 | */ |
| | 2056 | public function test_get_routes_cache_invalidated_on_register() { |
| | 2057 | $server = rest_get_server(); |
| | 2058 | |
| | 2059 | $routes_before = $server->get_routes(); |
| | 2060 | |
| | 2061 | register_rest_route( |
| | 2062 | 'test-cache-ns', |
| | 2063 | '/test-cache', |
| | 2064 | array( |
| | 2065 | 'methods' => array( 'GET' ), |
| | 2066 | 'callback' => '__return_true', |
| | 2067 | 'permission_callback' => '__return_true', |
| | 2068 | ) |
| | 2069 | ); |
| | 2070 | |
| | 2071 | $routes_after = $server->get_routes(); |
| | 2072 | |
| | 2073 | $this->assertArrayNotHasKey( '/test-cache-ns/test-cache', $routes_before ); |
| | 2074 | $this->assertArrayHasKey( '/test-cache-ns/test-cache', $routes_after ); |
| | 2075 | } |
| | 2076 | |
| | 2077 | /** |
| | 2078 | * @ticket 39473 |
| | 2079 | */ |
| | 2080 | public function test_get_routes_cached_result_matches_uncached() { |
| | 2081 | $server = rest_get_server(); |
| | 2082 | |
| | 2083 | // First call populates cache. |
| | 2084 | $first_call = $server->get_routes(); |
| | 2085 | // Second call returns from cache. |
| | 2086 | $second_call = $server->get_routes(); |
| | 2087 | |
| | 2088 | $this->assertSame( $first_call, $second_call, 'Cached routes should be identical to the initial result.' ); |
| | 2089 | } |
| | 2090 | |