DateComparator.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. * DateCompare compiles date comparisons.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class DateComparator extends Comparator
  17. {
  18. /**
  19. * @param string $test A comparison string
  20. *
  21. * @throws \InvalidArgumentException If the test is not understood
  22. */
  23. public function __construct(string $test)
  24. {
  25. if (!preg_match('#^\s*(==|!=|[<>]=?|after|since|before|until)?\s*(.+?)\s*$#i', $test, $matches)) {
  26. throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a date test.', $test));
  27. }
  28. try {
  29. $date = new \DateTime($matches[2]);
  30. $target = $date->format('U');
  31. } catch (\Exception $e) {
  32. throw new \InvalidArgumentException(sprintf('"%s" is not a valid date.', $matches[2]));
  33. }
  34. $operator = isset($matches[1]) ? $matches[1] : '==';
  35. if ('since' === $operator || 'after' === $operator) {
  36. $operator = '>';
  37. }
  38. if ('until' === $operator || 'before' === $operator) {
  39. $operator = '<';
  40. }
  41. $this->setOperator($operator);
  42. $this->setTarget($target);
  43. }
  44. }