Comparator.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. * @author Fabien Potencier <fabien@symfony.com>
  13. */
  14. class Comparator
  15. {
  16. private string $target;
  17. private string $operator;
  18. public function __construct(string $target, string $operator = '==')
  19. {
  20. if (!\in_array($operator, ['>', '<', '>=', '<=', '==', '!='])) {
  21. throw new \InvalidArgumentException(sprintf('Invalid operator "%s".', $operator));
  22. }
  23. $this->target = $target;
  24. $this->operator = $operator;
  25. }
  26. /**
  27. * Gets the target value.
  28. */
  29. public function getTarget(): string
  30. {
  31. return $this->target;
  32. }
  33. /**
  34. * Gets the comparison operator.
  35. */
  36. public function getOperator(): string
  37. {
  38. return $this->operator;
  39. }
  40. /**
  41. * Tests against the target.
  42. */
  43. public function test(mixed $test): bool
  44. {
  45. switch ($this->operator) {
  46. case '>':
  47. return $test > $this->target;
  48. case '>=':
  49. return $test >= $this->target;
  50. case '<':
  51. return $test < $this->target;
  52. case '<=':
  53. return $test <= $this->target;
  54. case '!=':
  55. return $test != $this->target;
  56. }
  57. return $test == $this->target;
  58. }
  59. }