BigNumberTimeConverterTest.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. declare(strict_types=1);
  3. namespace Ramsey\Uuid\Test\Converter\Time;
  4. use Brick\Math\BigInteger;
  5. use Ramsey\Uuid\Converter\Time\BigNumberTimeConverter;
  6. use Ramsey\Uuid\Exception\InvalidArgumentException;
  7. use Ramsey\Uuid\Test\TestCase;
  8. use Ramsey\Uuid\Type\Hexadecimal;
  9. use function sprintf;
  10. class BigNumberTimeConverterTest extends TestCase
  11. {
  12. public function testCalculateTimeReturnsArrayOfTimeSegments(): void
  13. {
  14. $seconds = BigInteger::of(5);
  15. $microseconds = BigInteger::of(3);
  16. $calculatedTime = BigInteger::zero()
  17. ->plus($seconds->multipliedBy(10000000))
  18. ->plus($microseconds->multipliedBy(10))
  19. ->plus(BigInteger::fromBase('01b21dd213814000', 16));
  20. $maskLow = BigInteger::fromBase('ffffffff', 16);
  21. $maskMid = BigInteger::fromBase('ffff', 16);
  22. $maskHi = BigInteger::fromBase('0fff', 16);
  23. $expected = sprintf('%04s', $calculatedTime->shiftedRight(48)->and($maskHi)->toBase(16));
  24. $expected .= sprintf('%04s', $calculatedTime->shiftedRight(32)->and($maskMid)->toBase(16));
  25. $expected .= sprintf('%08s', $calculatedTime->and($maskLow)->toBase(16));
  26. $converter = new BigNumberTimeConverter();
  27. $returned = $converter->calculateTime((string) $seconds, (string) $microseconds);
  28. $this->assertInstanceOf(Hexadecimal::class, $returned);
  29. $this->assertSame($expected, $returned->toString());
  30. }
  31. public function testConvertTime(): void
  32. {
  33. $converter = new BigNumberTimeConverter();
  34. $returned = $converter->convertTime(new Hexadecimal('1e1c57dff6f8cb0'));
  35. $this->assertSame('1341368074', $returned->getSeconds()->toString());
  36. }
  37. public function testCalculateTimeThrowsExceptionWhenSecondsIsNotOnlyDigits(): void
  38. {
  39. $converter = new BigNumberTimeConverter();
  40. $this->expectException(InvalidArgumentException::class);
  41. $this->expectExceptionMessage(
  42. 'Value must be a signed integer or a string containing only digits '
  43. . '0-9 and, optionally, a sign (+ or -)'
  44. );
  45. $converter->calculateTime('12.34', '5678');
  46. }
  47. public function testCalculateTimeThrowsExceptionWhenMicrosecondsIsNotOnlyDigits(): void
  48. {
  49. $converter = new BigNumberTimeConverter();
  50. $this->expectException(InvalidArgumentException::class);
  51. $this->expectExceptionMessage(
  52. 'Value must be a signed integer or a string containing only digits '
  53. . '0-9 and, optionally, a sign (+ or -)'
  54. );
  55. $converter->calculateTime('1234', '56.78');
  56. }
  57. }