[A-Za-z0-9]{1,64})/(?P[0-9]{8})', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( self::class, 'lookup' ), 'permission_callback' => array( self::class, 'permitted' ), 'args' => array( 'token' => array( 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_key', ), 'cep' => array( 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_key', 'validate_callback' => static fn( $value ): bool => 1 === preg_match( '/^[0-9]{8}$/', (string) $value ), ), ), ) ); } /** * Reject anything that does not carry a live token. * * @param WP_REST_Request $request Incoming request. * * @return true|WP_Error True when the token checks out. */ public static function permitted( WP_REST_Request $request ): bool|WP_Error { if ( Cepis_Woo_Token::verify( (string) $request['token'] ) ) { return true; } return new WP_Error( 'cepis_invalid_token', __( 'Lookup token missing, invalid or expired. Reload the page.', 'cepis-woocommerce' ), array( 'status' => 403 ) ); } /** * Answer one lookup. * * @param WP_REST_Request $request Incoming request. */ public static function lookup( WP_REST_Request $request ): WP_REST_Response { $result = Cepis_Woo_Lookup::resolve( (string) $request['cep'] ); $response = new WP_REST_Response( $result['body'], $result['status'] ); $response->header( 'Cache-Control', 'no-store' ); if ( null !== $result['retry_after'] ) { $response->header( 'Retry-After', (string) $result['retry_after'] ); } return $response; } /** * The API root to hand the browser, with a live token already in it. * * Shaped so that appending `/{cep}` to it reaches this route, which is what * the widget does with its `baseUrl`. */ public static function base_url(): string { return untrailingslashit( rest_url( self::NAMESPACE_V1 . '/lookup/' . Cepis_Woo_Token::create() ) ); } }