TimeFactory.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\AppFramework\Utility;
  9. use OCP\AppFramework\Utility\ITimeFactory;
  10. /**
  11. * Use this to get a timestamp or DateTime object in code to remain testable
  12. *
  13. * @since 8.0.0
  14. * @since 27.0.0 Implements the \Psr\Clock\ClockInterface interface
  15. * @ref https://www.php-fig.org/psr/psr-20/#21-clockinterface
  16. */
  17. class TimeFactory implements ITimeFactory {
  18. protected \DateTimeZone $timezone;
  19. public function __construct() {
  20. $this->timezone = new \DateTimeZone('UTC');
  21. }
  22. /**
  23. * @return int the result of a call to time()
  24. * @since 8.0.0
  25. * @deprecated 26.0.0 {@see ITimeFactory::now()}
  26. */
  27. public function getTime(): int {
  28. return time();
  29. }
  30. /**
  31. * @param string $time
  32. * @param \DateTimeZone $timezone
  33. * @return \DateTime
  34. * @since 15.0.0
  35. * @deprecated 26.0.0 {@see ITimeFactory::now()}
  36. */
  37. public function getDateTime(string $time = 'now', ?\DateTimeZone $timezone = null): \DateTime {
  38. return new \DateTime($time, $timezone);
  39. }
  40. public function now(): \DateTimeImmutable {
  41. return new \DateTimeImmutable('now', $this->timezone);
  42. }
  43. public function withTimeZone(\DateTimeZone $timezone): static {
  44. $clone = clone $this;
  45. $clone->timezone = $timezone;
  46. return $clone;
  47. }
  48. public function getTimeZone(?string $timezone = null): \DateTimeZone {
  49. if ($timezone !== null) {
  50. return new \DateTimeZone($timezone);
  51. }
  52. return $this->timezone;
  53. }
  54. }