116 lines
3.1 KiB
PHP
116 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace App\Helpers;
|
|
|
|
|
|
use Carbon\Carbon;
|
|
use InvalidArgumentException;
|
|
|
|
class LengthFormatter
|
|
{
|
|
/**
|
|
* @string length
|
|
*/
|
|
private $_length;
|
|
|
|
// @param string $length formatted H:i:s.u (can be > 24 hours)
|
|
public function __construct($length)
|
|
{
|
|
$this->_length = $length;
|
|
}
|
|
|
|
public function toSeconds() {
|
|
if (!preg_match('/^[0-9]{2}:[0-9]{2}:[0-9]{2}/', $this->_length)) {
|
|
return $this->_length;
|
|
}
|
|
|
|
$pieces = explode(':', $this->_length);
|
|
|
|
$hours = $minutes = 0;
|
|
if (intval($pieces[0]) !== 0) {
|
|
$hours = intval(ltrim($pieces[0], '0')) * 3600;
|
|
}
|
|
if (intval($pieces[1]) !== 0) {
|
|
$minutes = intval(ltrim($pieces[1], '0')) * 60;
|
|
}
|
|
|
|
return $hours + $minutes + floatval($pieces[2]);
|
|
}
|
|
|
|
public function format()
|
|
{
|
|
if (!preg_match('/^[0-9]{2}:[0-9]{2}:[0-9]{2}/', $this->_length)) {
|
|
return $this->_length;
|
|
}
|
|
|
|
$pieces = explode(':', $this->_length);
|
|
|
|
$seconds = round($pieces[2], 1);
|
|
$seconds = number_format($seconds, 1);
|
|
[$seconds, $milliStr] = explode('.', $seconds);
|
|
|
|
if (intval($pieces[0]) !== 0) {
|
|
$hours = ltrim($pieces[0], '0');
|
|
}
|
|
|
|
$minutes = $pieces[1];
|
|
// length is less than 1 hour
|
|
if (!isset($hours)) {
|
|
if (intval($minutes) !== 0) {
|
|
$minutes = ltrim($minutes, '0');
|
|
}
|
|
// length is less than 1 minute
|
|
else {
|
|
unset($minutes);
|
|
}
|
|
}
|
|
|
|
if (isset($hours, $minutes, $seconds)) {
|
|
$time = sprintf('%d:%02d:%02d.%s', $hours, $minutes, $seconds, $milliStr);
|
|
} elseif (isset($minutes, $seconds)) {
|
|
$time = sprintf('%d:%02d.%s', $minutes, $seconds, $milliStr);
|
|
} else {
|
|
$time = sprintf('%d.%s', $seconds, $milliStr);
|
|
}
|
|
|
|
return $time;
|
|
}
|
|
|
|
|
|
public static function generateStringTimeFilled(Carbon $showStartDate, Carbon $showEndDate): string
|
|
{
|
|
$interval = $showEndDate->diff($showStartDate);
|
|
|
|
return sprintf(
|
|
"%d years %d mons %d days %d hours %d mins %.1f secs",
|
|
$interval->y,
|
|
$interval->m,
|
|
$interval->d,
|
|
$interval->h,
|
|
$interval->i,
|
|
$interval->s
|
|
);
|
|
}
|
|
|
|
public static function contentLengthToSeconds(string $contentLength): float|int
|
|
{
|
|
|
|
// Initialize total seconds
|
|
// Use regex to extract hours, minutes, seconds, and milliseconds
|
|
preg_match('/(\d+):(\d+):([\d.]+)/', $contentLength, $matches);
|
|
|
|
if (!$matches) {
|
|
throw new InvalidArgumentException("Invalid time format");
|
|
}
|
|
|
|
// Extract components
|
|
$hours = (int)$matches[1];
|
|
$minutes = (int)$matches[2];
|
|
$seconds = (float)$matches[3]; // Includes fractional seconds
|
|
|
|
// Convert everything to total seconds
|
|
$totalSeconds = ($hours * 3600) + ($minutes * 60) + $seconds;
|
|
|
|
return $totalSeconds;
|
|
}
|
|
}
|