container = $container; $this->controllers = $controllers; } /** * {@inheritdoc} */ public function register(): void { add_action( 'rest_api_init', array( $this, 'register_routes' ) ); add_filter( 'rest_post_dispatch', array( $this, 'no_cache' ), 10, 3 ); } /** * Marks every InterviewNea response private and uncacheable: they carry personal data and tokens. * * @since 0.1.0 * * @param \WP_HTTP_Response $response Response. * @param \WP_REST_Server $server Server. * @param \WP_REST_Request $request Request. * @return \WP_HTTP_Response */ public function no_cache( $response, $server, $request ) { unset( $server ); if ( 0 === strpos( (string) $request->get_route(), '/interviewnea/v1/' ) && $response instanceof \WP_HTTP_Response ) { $response->header( 'Cache-Control', 'private, no-store, no-cache, max-age=0' ); $response->header( 'Pragma', 'no-cache' ); } return $response; } /** * Registers the routes of all controllers. * * @since 0.1.0 * * @return void */ public function register_routes(): void { if ( ! $this->needed() ) { return; } foreach ( $this->controllers as $id ) { $this->container->get( $id )->register_routes(); } } /** * Tells whether the routes are needed for this request. * * `rest_api_init` runs for every REST request on the site, such as those of the block editor. * Building all the controllers for a request that is about someone else's route is wasted work, so * they are only built when the request is for InterviewNea, or when it names no route (the index, * command line and internal calls). * * @since 0.1.0 * * @return bool */ private function needed(): bool { $route = ''; if ( isset( $GLOBALS['wp'] ) && is_object( $GLOBALS['wp'] ) && isset( $GLOBALS['wp']->query_vars['rest_route'] ) ) { $route = (string) $GLOBALS['wp']->query_vars['rest_route']; } if ( '' === $route || '/' === $route ) { return true; } return 0 === strpos( '/' . ltrim( $route, '/' ), '/interviewnea/' ); } }