From 4dcb6b6ebed778a19e2a43b5e0da3e582eb8b26c Mon Sep 17 00:00:00 2001 From: Brian Rogers Date: Mon, 27 Mar 2023 10:19:42 -0600 Subject: [PATCH] adding a clamp function --- src/helpers/global_functions.php | 43 +++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/src/helpers/global_functions.php b/src/helpers/global_functions.php index 51c9876..03bec41 100644 --- a/src/helpers/global_functions.php +++ b/src/helpers/global_functions.php @@ -15,6 +15,47 @@ require_once "functions/temperatures.php"; | */ +if (! function_exists('clamp')) { + /** + * Ensure a numerical value is between two bounds. + * + * @since 1.0.0 + * + * @param int|float|string $number The value to be clamped between two other values. + * @param int|float|string $minNumber The miminum value for clamping bounds. + * @param int|float|string $maxNumber The maximum value for clamping bounds. + * + * @throws \Exception + * + * @return int|float + */ + function clamp($number, $minNumber, $maxNumber) + { + if (! is_numeric($number)) { + throw new Exception('Clamp number must be numeric in value.'); + } + + if (! is_numeric($minNumber)) { + throw new Exception('Clamped minimum number must be numeric in value.'); + } + + if (! is_numeric($maxNumber)) { + throw new Exception('Clamped maximum number must be numeric in value.'); + } + + $returnValue = $number; + if ($minNumber >= $number) { + $returnValue = $minNumber; + } + + if ($maxNumber <= $number) { + $returnValue = $maxNumber; + } + + return $returnValue; + } +} + if (! function_exists('humanBytes')) { /** * Convert bytes to a human-friendly format. @@ -195,7 +236,7 @@ if (! function_exists('maybe_unserialize')) { * * @param mixed $data * - * @return mixed + * @return array|string|bool */ function maybe_unserialize($data) {