DateComparator.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 = $matches[1] ?? '==';
  35. if ('since' === $operator || 'after' === $operator) {
  36. $operator = '>';
  37. }
  38. if ('until' === $operator || 'before' === $operator) {
  39. $operator = '<';
  40. }
  41. parent::__construct($target, $operator);
  42. }
  43. }