LengthFormatter.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. class LengthFormatter
  3. {
  4. /**
  5. * @string length
  6. */
  7. private $_length;
  8. /*
  9. * @param string $length formatted H:i:s.u (can be > 24 hours)
  10. */
  11. public function __construct($length)
  12. {
  13. $this->_length = $length;
  14. }
  15. public function format()
  16. {
  17. if (!preg_match("/^[0-9]{2}:[0-9]{2}:[0-9]{2}/", $this->_length)) {
  18. return $this->_length;
  19. }
  20. $pieces = explode(":", $this->_length);
  21. $seconds = round($pieces[2], 1);
  22. $seconds = number_format($seconds, 1);
  23. list($seconds, $milliStr) = explode(".", $seconds);
  24. if (intval($pieces[0]) !== 0) {
  25. $hours = ltrim($pieces[0], "0");
  26. }
  27. $minutes = $pieces[1];
  28. //length is less than 1 hour
  29. if (!isset($hours)) {
  30. if (intval($minutes) !== 0) {
  31. $minutes = ltrim($minutes, "0");
  32. }
  33. //length is less than 1 minute
  34. else {
  35. unset($minutes);
  36. }
  37. }
  38. if (isset($hours) && isset($minutes) && isset($seconds)) {
  39. $time = sprintf("%d:%02d:%02d.%s", $hours, $minutes, $seconds, $milliStr);
  40. } elseif (isset($minutes) && isset($seconds)) {
  41. $time = sprintf("%d:%02d.%s", $minutes, $seconds, $milliStr);
  42. } else {
  43. $time = sprintf("%d.%s", $seconds, $milliStr);
  44. }
  45. return $time;
  46. }
  47. }