ClockAwareTrait.php 841 B

1234567891011121314151617181920212223242526272829303132333435363738
  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\Clock;
  11. use Psr\Clock\ClockInterface;
  12. use Symfony\Contracts\Service\Attribute\Required;
  13. /**
  14. * A trait to help write time-sensitive classes.
  15. *
  16. * @author Nicolas Grekas <p@tchwork.com>
  17. */
  18. trait ClockAwareTrait
  19. {
  20. private readonly ClockInterface $clock;
  21. #[Required]
  22. public function setClock(ClockInterface $clock): void
  23. {
  24. $this->clock = $clock;
  25. }
  26. protected function now(): DatePoint
  27. {
  28. $now = ($this->clock ??= new Clock())->now();
  29. return $now instanceof DatePoint ? $now : DatePoint::createFromInterface($now);
  30. }
  31. }