Util.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. /**
  3. * SCSSPHP
  4. *
  5. * @copyright 2012-2015 Leaf Corcoran
  6. *
  7. * @license http://opensource.org/licenses/MIT MIT
  8. *
  9. * @link http://leafo.github.io/scssphp
  10. */
  11. namespace Leafo\ScssPhp;
  12. use Leafo\ScssPhp\Base\Range;
  13. /**
  14. * Utilties
  15. *
  16. * @author Anthon Pang <anthon.pang@gmail.com>
  17. */
  18. class Util
  19. {
  20. /**
  21. * Asserts that `value` falls within `range` (inclusive), leaving
  22. * room for slight floating-point errors.
  23. *
  24. * @param string $name The name of the value. Used in the error message.
  25. * @param Range $range Range of values.
  26. * @param array $value The value to check.
  27. * @param string $unit The unit of the value. Used in error reporting.
  28. *
  29. * @return mixed `value` adjusted to fall within range, if it was outside by a floating-point margin.
  30. *
  31. * @throws \Exception
  32. */
  33. public static function checkRange($name, Range $range, $value, $unit = '')
  34. {
  35. $val = $value[1];
  36. $grace = new Range(-1.0E-5, 1.0E-5);
  37. if ($range->includes($val)) {
  38. return $val;
  39. }
  40. if ($grace->includes($val - $range->first)) {
  41. return $range->first;
  42. }
  43. if ($grace->includes($val - $range->last)) {
  44. return $range->last;
  45. }
  46. throw new \Exception("{$name} {$val} must be between {$range->first} and {$range->last}{$unit}");
  47. }
  48. }