You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.4 KiB

3 years ago
  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. $this->setOperator($operator);
  42. $this->setTarget($target);
  43. }
  44. }