NumberComparator.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Symfony\Component\Finder\Comparator;
  3. /*
  4. * This file is part of the Symfony framework.
  5. *
  6. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  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.potencier@symfony-project.com> PHP port
  26. * @author Richard Clamp <richardc@unixbeard.net> Perl version
  27. * @copyright 2004-2005 Fabien Potencier <fabien.potencier@symfony-project.com>
  28. * @copyright 2002 Richard Clamp <richardc@unixbeard.net>
  29. * @see http://physics.nist.gov/cuu/Units/binary.html
  30. */
  31. class NumberComparator extends Comparator
  32. {
  33. /**
  34. * Constructor.
  35. *
  36. * @param string $test A comparison string
  37. *
  38. * @throws \InvalidArgumentException If the test is not understood
  39. */
  40. public function __construct($test)
  41. {
  42. if (!preg_match('#^\s*([<>=]=?)?\s*([0-9\.]+)\s*([kmg]i?)?\s*$#i', $test, $matches)) {
  43. throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a number test.', $test));
  44. }
  45. $target = $matches[2];
  46. $magnitude = strtolower(isset($matches[3]) ? $matches[3] : '');
  47. switch ($magnitude) {
  48. case 'k':
  49. $target *= 1000;
  50. break;
  51. case 'ki':
  52. $target *= 1024;
  53. break;
  54. case 'm':
  55. $target *= 1000000;
  56. break;
  57. case 'mi':
  58. $target *= 1024*1024;
  59. break;
  60. case 'g':
  61. $target *= 1000000000;
  62. break;
  63. case 'gi':
  64. $target *= 1024*1024*1024;
  65. break;
  66. }
  67. $this->setTarget($target);
  68. $this->setOperator(isset($matches[1]) ? $matches[1] : '==');
  69. }
  70. }