NumberComparator.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Finder\Comparator;
  11. /**
  12. * NumberComparator compiles a simple comparison to an anonymous
  13. * subroutine, which you can call with a value to be tested again.
  14. *
  15. * Now this would be very pointless, if NumberCompare didn't understand
  16. * magnitudes.
  17. *
  18. * The target value may use magnitudes of kilobytes (k, ki),
  19. * megabytes (m, mi), or gigabytes (g, gi). Those suffixed
  20. * with an i use the appropriate 2**n version in accordance with the
  21. * IEC standard: http://physics.nist.gov/cuu/Units/binary.html
  22. *
  23. * Based on the Perl Number::Compare module.
  24. *
  25. * @author Fabien Potencier <fabien@symfony.com> PHP port
  26. * @author Richard Clamp <richardc@unixbeard.net> Perl version
  27. * @copyright 2004-2005 Fabien Potencier <fabien@symfony.com>
  28. * @copyright 2002 Richard Clamp <richardc@unixbeard.net>
  29. *
  30. * @see http://physics.nist.gov/cuu/Units/binary.html
  31. */
  32. class NumberComparator extends Comparator
  33. {
  34. /**
  35. * @param string|null $test A comparison string or null
  36. *
  37. * @throws \InvalidArgumentException If the test is not understood
  38. */
  39. public function __construct(?string $test)
  40. {
  41. if (null === $test || !preg_match('#^\s*(==|!=|[<>]=?)?\s*([0-9\.]+)\s*([kmg]i?)?\s*$#i', $test, $matches)) {
  42. throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a number test.', $test ?? 'null'));
  43. }
  44. $target = $matches[2];
  45. if (!is_numeric($target)) {
  46. throw new \InvalidArgumentException(sprintf('Invalid number "%s".', $target));
  47. }
  48. if (isset($matches[3])) {
  49. // magnitude
  50. switch (strtolower($matches[3])) {
  51. case 'k':
  52. $target *= 1000;
  53. break;
  54. case 'ki':
  55. $target *= 1024;
  56. break;
  57. case 'm':
  58. $target *= 1000000;
  59. break;
  60. case 'mi':
  61. $target *= 1024 * 1024;
  62. break;
  63. case 'g':
  64. $target *= 1000000000;
  65. break;
  66. case 'gi':
  67. $target *= 1024 * 1024 * 1024;
  68. break;
  69. }
  70. }
  71. parent::__construct($target, $matches[1] ?: '==');
  72. }
  73. }