DateComparator.php 1.4 KB

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