ToStringTest.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of the Carbon package.
  5. *
  6. * (c) Brian Nesbitt <brian@nesbot.com>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Tests\CarbonInterval;
  12. use Carbon\CarbonInterval;
  13. use Tests\AbstractTestCase;
  14. class ToStringTest extends AbstractTestCase
  15. {
  16. public function testDefault()
  17. {
  18. CarbonInterval::setLocale('en');
  19. $ci = CarbonInterval::create(11, 1, 2, 5, 22, 33, 55);
  20. $this->assertSame('11 years 1 month 2 weeks 5 days 22 hours 33 minutes 55 seconds:abc', $ci.':abc');
  21. }
  22. public function testDefaultWithMicroseconds()
  23. {
  24. CarbonInterval::setLocale('en');
  25. $ci = CarbonInterval::create(11, 1, 2, 5, 22, 33, 55, 12345);
  26. $this->assertSame('11 years 1 month 2 weeks 5 days 22 hours 33 minutes 55 seconds:abc', $ci.':abc');
  27. }
  28. public function testOverrideSimple()
  29. {
  30. $ci = CarbonInterval::create(0, 0, 0, 0, 22, 33, 55);
  31. $ci->settings(['toStringFormat' => '%H:%I:%S']);
  32. $this->assertSame('22:33:55:abc', $ci.':abc');
  33. }
  34. public function testOverrideWithMicroseconds()
  35. {
  36. $ci = CarbonInterval::create(11, 1, 2, 5, 22, 33, 55, 12345);
  37. $ci->settings(['toStringFormat' => '%R%Y-%M-%D %H:%I:%S.%F']);
  38. $this->assertSame('+11-01-19 22:33:55.012345:abc', $ci.':abc');
  39. }
  40. public function testOverrideWithInvert()
  41. {
  42. $ci = CarbonInterval::create(11, 1, 2, 5, 22, 33, 55)->invert();
  43. $ci->settings(['toStringFormat' => '%R%Y-%M-%D %H:%I:%S']);
  44. $this->assertSame('-11-01-19 22:33:55:abc', $ci.':abc');
  45. }
  46. public function testClosure()
  47. {
  48. $ci = CarbonInterval::create(11);
  49. $this->assertSame('11 years:abc', $ci.':abc');
  50. CarbonInterval::setToStringFormat('%Y');
  51. $this->assertSame('11:abc', $ci.':abc');
  52. $ci->settings(['toStringFormat' => static function (CarbonInterval $interval) {
  53. return 'Y'.($interval->years * 2);
  54. }]);
  55. $this->assertSame('Y22:abc', $ci.':abc');
  56. CarbonInterval::resetToStringFormat();
  57. }
  58. }