<?php
/**
 * Request helpers.
 *
 * @package SubmissionInbox
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Centralizes read-only request access for admin filters and routing.
 */
class SUBIN_Request {
	/**
	 * Read a sanitized text value from the query string.
	 *
	 * @param string $key Request key.
	 * @param string $fallback Fallback value.
	 * @return string
	 */
	public static function get_text( $key, $fallback = '' ) {
		if ( ! isset( $_GET[ $key ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Centralized query parameter helper; public wrappers define read-only or nonce-protected action usage.
			return $fallback;
		}

		$value = wp_unslash( $_GET[ $key ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Centralized query parameter helper; sanitized below after unslashing.
		if ( is_array( $value ) ) {
			return $fallback;
		}

		return sanitize_text_field( $value );
	}

	/**
	 * Read a sanitized key from the query string.
	 *
	 * @param string $key Request key.
	 * @param string $fallback Fallback value.
	 * @return string
	 */
	public static function get_key( $key, $fallback = '' ) {
		return sanitize_key( self::get_text( $key, $fallback ) );
	}

	/**
	 * Read an absolute integer from the query string.
	 *
	 * @param string $key Request key.
	 * @param int    $fallback Fallback value.
	 * @return int
	 */
	public static function get_absint( $key, $fallback = 0 ) {
		return absint( self::get_text( $key, (string) $fallback ) );
	}

	/**
	 * Read a sanitized text value from a nonce-protected action query string.
	 *
	 * @param string $key Request key.
	 * @param string $fallback Fallback value.
	 * @return string
	 */
	public static function action_text( $key, $fallback = '' ) {
		return self::get_text( $key, $fallback );
	}

	/**
	 * Read a sanitized key from a nonce-protected action query string.
	 *
	 * @param string $key Request key.
	 * @param string $fallback Fallback value.
	 * @return string
	 */
	public static function action_key( $key, $fallback = '' ) {
		return sanitize_key( self::action_text( $key, $fallback ) );
	}

	/**
	 * Read an absolute integer from a nonce-protected action query string.
	 *
	 * @param string $key Request key.
	 * @param int    $fallback Fallback value.
	 * @return int
	 */
	public static function action_absint( $key, $fallback = 0 ) {
		return absint( self::action_text( $key, (string) $fallback ) );
	}

	/**
	 * Determine whether a query string key exists.
	 *
	 * @param string $key Request key.
	 * @return bool
	 */
	public static function query_has( $key ) {
		return isset( $_GET[ $key ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only query parameter presence helper.
	}
}
