You are here

public static function FractionDecimal::checkInBounds in Fraction 8

Same name and namespace in other branches
  1. 2.x src/Element/FractionDecimal.php \Drupal\fraction\Element\FractionDecimal::checkInBounds()

Helper method to check if a given value is in between two other values.

Uses BCMath and strings for arbitrary-precision operations where possible.

Parameters

string $value: The value to check.

string $min: The minimum bound.

string $max: The maximum bound.

int $scale: Optional scale integer to pass into bcsub() if BCMath is used.

Return value

bool Returns TRUE if $number is between $min and $max, FALSE otherwise.

1 call to FractionDecimal::checkInBounds()
FractionDecimal::validateDecimal in src/Element/FractionDecimal.php
Validates the fraction_decimal element.

File

src/Element/FractionDecimal.php, line 156

Class

FractionDecimal
Provides a fraction decimal form element.

Namespace

Drupal\fraction\Element

Code

public static function checkInBounds($value, $min, $max, $scale = 0) {

  // If BCMath isn't available, let PHP handle it via normal float comparison.
  if (!function_exists('bcsub')) {
    return $value > $max || $value < $min ? FALSE : TRUE;
  }

  // Subtract the minimum bound and maximum bounds from the value.
  $diff_min = bcsub($value, $min, $scale);
  $diff_max = bcsub($value, $max, $scale);

  // If either have a difference of zero, then the value is in bounds.
  if ($diff_min == 0 || $diff_max == 0) {
    return TRUE;
  }

  // If the first character of $diff_min is a negative sign (-), then the
  // value is less than the minimum, and therefore out of bounds.
  if (substr($diff_min, 0, 1) == '-') {
    return FALSE;
  }

  // If the first character of $diff_max is a number, then the value is
  // greater than the maximum, and therefore out of bounds.
  if (is_numeric(substr($diff_max, 0, 1))) {
    return FALSE;
  }

  // Assume the value is in bounds if none of the above said otherwise.
  return TRUE;
}