Duration.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of phpunit/php-timer.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  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 SebastianBergmann\Timer;
  11. use function floor;
  12. use function sprintf;
  13. /**
  14. * @psalm-immutable
  15. */
  16. final class Duration
  17. {
  18. private readonly float $nanoseconds;
  19. private readonly int $hours;
  20. private readonly int $minutes;
  21. private readonly int $seconds;
  22. private readonly int $milliseconds;
  23. public static function fromMicroseconds(float $microseconds): self
  24. {
  25. return new self($microseconds * 1000);
  26. }
  27. public static function fromNanoseconds(float $nanoseconds): self
  28. {
  29. return new self($nanoseconds);
  30. }
  31. private function __construct(float $nanoseconds)
  32. {
  33. $this->nanoseconds = $nanoseconds;
  34. $timeInMilliseconds = $nanoseconds / 1000000;
  35. $hours = floor($timeInMilliseconds / 60 / 60 / 1000);
  36. $hoursInMilliseconds = $hours * 60 * 60 * 1000;
  37. $minutes = floor($timeInMilliseconds / 60 / 1000) % 60;
  38. $minutesInMilliseconds = $minutes * 60 * 1000;
  39. $seconds = floor(($timeInMilliseconds - $hoursInMilliseconds - $minutesInMilliseconds) / 1000);
  40. $secondsInMilliseconds = $seconds * 1000;
  41. $milliseconds = $timeInMilliseconds - $hoursInMilliseconds - $minutesInMilliseconds - $secondsInMilliseconds;
  42. $this->hours = (int) $hours;
  43. $this->minutes = $minutes;
  44. $this->seconds = (int) $seconds;
  45. $this->milliseconds = (int) $milliseconds;
  46. }
  47. public function asNanoseconds(): float
  48. {
  49. return $this->nanoseconds;
  50. }
  51. public function asMicroseconds(): float
  52. {
  53. return $this->nanoseconds / 1000;
  54. }
  55. public function asMilliseconds(): float
  56. {
  57. return $this->nanoseconds / 1000000;
  58. }
  59. public function asSeconds(): float
  60. {
  61. return $this->nanoseconds / 1000000000;
  62. }
  63. public function asString(): string
  64. {
  65. $result = '';
  66. if ($this->hours > 0) {
  67. $result = sprintf('%02d', $this->hours) . ':';
  68. }
  69. $result .= sprintf('%02d', $this->minutes) . ':';
  70. $result .= sprintf('%02d', $this->seconds);
  71. if ($this->milliseconds > 0) {
  72. $result .= '.' . sprintf('%03d', $this->milliseconds);
  73. }
  74. return $result;
  75. }
  76. }