You are here

public function HMSService::seconds_to_formatted in HMS Field 8

Returns a formatted string form the number of seconds.

Parameters

$seconds:

string $format:

bool|TRUE $leading_zero:

Return value

mixed

Overrides HMSServiceInterface::seconds_to_formatted

File

src/HMSService.php, line 252

Class

HMSService
Provides a service to handle various hms related functionality.

Namespace

Drupal\hms_field

Code

public function seconds_to_formatted($seconds, $format = 'h:mm', $leading_zero = TRUE) {

  // Return NULL on empty string.
  if ($seconds === '' || is_null($seconds)) {
    return NULL;
  }
  $factor = $this
    ->factor_map();

  // We need factors, biggest first.
  arsort($factor, SORT_NUMERIC);
  $values = [];
  $left_over = $seconds;
  $str = '';
  if ($seconds < 0) {
    $str .= '-';
    $left_over = abs($left_over);
  }

  // Space separated format
  if ($format == 'hms') {
    foreach ($factor as $key => $val) {
      if ($left_over == 0) {
        break;
      }
      $values[$key] = floor($left_over / $factor[$key]);
      if ($values[$key]) {
        $left_over -= $values[$key] * $factor[$key];
        $str .= $values[$key] . $key . ' ';
      }
    }
  }
  else {
    foreach ($factor as $key => $val) {
      if (strpos($format, $key) === FALSE) {
        continue;

        // Not in our format, please go on, so we can plus this on a value in our format.
      }
      if ($left_over == 0) {
        $values[$key] = 0;
        continue;
      }
      $values[$key] = floor($left_over / $factor[$key]);
      $left_over -= $values[$key] * $factor[$key];
    }
    $format = explode(':', $format);
    foreach ($format as $key) {
      if (!$leading_zero && (empty($values[substr($key, 0, 1)]) || !$values[substr($key, 0, 1)])) {
        continue;
      }
      $leading_zero = TRUE;
      $str .= sprintf('%0' . strlen($key) . 'd', $values[substr($key, 0, 1)]) . ':';
    }
    if (!strlen($str)) {
      $key = array_pop($format);
      $str = sprintf('%0' . strlen($key) . 'd', 0) . ':';
    }
  }
  return substr($str, 0, -1);
}