repository = $repository; $this->options = $options; $this->cache = $cache; } /** * Registers the REST route. */ public function register_routes(): void { register_rest_route( 'mapsemble/v1', '/filter/options', array( 'methods' => 'GET', 'callback' => array( $this, 'handle' ), 'permission_callback' => '__return_true', 'args' => array( 'mapId' => array( 'type' => 'string' ), 'filter' => array( 'type' => 'string' ), 'search' => array( 'type' => 'string' ), ), ) ); } /** * Builds the options response. * * @param WP_REST_Request $request The request. */ public function handle( WP_REST_Request $request ): WP_REST_Response { $config = $this->repository->find_by_map_id( (string) $request->get_param( 'mapId' ) ); if ( null === $config ) { return $this->respond( array() ); } if ( $config->is_hosted() ) { return $this->hosted_map_refusal(); } $filter = (string) $request->get_param( 'filter' ); $search = (string) $request->get_param( 'search' ); return $this->cache->remember( 'filter/options', $config, $request, array( 'filter' => $filter, 'search' => $search, ), fn (): WP_REST_Response => $this->respond( $this->options->options_for( $config, $filter, $search ) ) ); } /** * Wraps options with the CORS header, as an object even when empty. * * @param array $options value => label. */ private function respond( array $options ): WP_REST_Response { $response = new WP_REST_Response( (object) $options ); $response->header( 'Access-Control-Allow-Origin', '*' ); return $response; } }