NumberComparator.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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|int $test A comparison string or an integer
  36. *
  37. * @throws \InvalidArgumentException If the test is not understood
  38. */
  39. public function __construct($test)
  40. {
  41. if (!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));
  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. $this->setTarget($target);
  72. $this->setOperator(isset($matches[1]) ? $matches[1] : '==');
  73. }
  74. }