| 1: | <?php |
| 2: | |
| 3: | declare(strict_types=1); |
| 4: | |
| 5: | /** |
| 6: | * This file is part of the Nexus framework. |
| 7: | * |
| 8: | * (c) John Paul E. Balandan, CPA <paulbalandan@gmail.com> |
| 9: | * |
| 10: | * For the full copyright and license information, please view |
| 11: | * the LICENSE file that was distributed with this source code. |
| 12: | */ |
| 13: | |
| 14: | namespace Nexus\Clock\Extension; |
| 15: | |
| 16: | use Nexus\Clock\Clock; |
| 17: | use Nexus\Clock\FrozenClock; |
| 18: | use Nexus\Clock\InternalClock; |
| 19: | use Psr\Clock\ClockInterface; |
| 20: | |
| 21: | /** |
| 22: | * A trait to help write time-sensitive classes. |
| 23: | * |
| 24: | * @phpstan-require-implements ClockAwareInterface |
| 25: | */ |
| 26: | trait ClockAware |
| 27: | { |
| 28: | private ?ClockInterface $clock = null; |
| 29: | |
| 30: | public function setClock(?ClockInterface $clock): self |
| 31: | { |
| 32: | $this->clock = $clock; |
| 33: | |
| 34: | return $this; |
| 35: | } |
| 36: | |
| 37: | public function getClock(): Clock |
| 38: | { |
| 39: | if (null === $this->clock) { |
| 40: | return InternalClock::getCurrent(); |
| 41: | } |
| 42: | |
| 43: | if (! $this->clock instanceof Clock) { |
| 44: | return new FrozenClock($this->clock->now()); |
| 45: | } |
| 46: | |
| 47: | return $this->clock; |
| 48: | } |
| 49: | |
| 50: | /** |
| 51: | * Gets the current timestamp. |
| 52: | */ |
| 53: | private function now(): int |
| 54: | { |
| 55: | return $this->getClock()->now()->getTimestamp(); |
| 56: | } |
| 57: | } |
| 58: |