<?php

if (! function_exists('sanitize_request_value')) {
    /**
     * Recursively normalize request values without applying output encoding.
     */
    function sanitize_request_value($value)
    {
        if (is_array($value)) {
            foreach ($value as $key => $item) {
                $value[$key] = sanitize_request_value($item);
            }

            return $value;
        }

        if (! is_string($value)) {
            return $value;
        }

        $value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $value) ?? $value;

        return trim($value);
    }
}

if (! function_exists('require_env')) {
    /**
     * Fetch an environment variable and fail closed when it is missing.
     */
    function require_env(string $key): string
    {
        $value = env($key);

        if ($value === null || $value === '') {
            throw new RuntimeException(sprintf('Missing required environment variable: %s', $key));
        }

        return (string) $value;
    }
}
