Completed
Push — developer ( b33bdc...d235c9 )
by Błażej
26:07 queued 12:56
created

Time   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 90.91%

Importance

Changes 0
Metric Value
wmc 14
lcom 0
cbo 1
dl 0
loc 62
ccs 20
cts 22
cp 0.9091
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A secondsToDecimal() 0 6 1
A timeToDecimal() 0 5 1
C formatToHourText() 0 23 12
1
<?php
2
/**
3
 * Tools for time class.
4
 *
5
 * @copyright YetiForce Sp. z o.o
6
 * @license   YetiForce Public License 3.0 (licenses/LicenseEN.txt or yetiforce.com)
7
 * @author    Rafał Pospiech <[email protected]>
8
 */
9
10
namespace App\Fields;
11
12
/**
13
 * Time class.
14
 */
15
class Time
16
{
17
	/**
18
	 * Convert seconds to decimal time format.
19
	 *
20
	 * @param int $seconds
21
	 *
22
	 * @return float
23
	 */
24 2
	public static function secondsToDecimal(int $seconds)
25
	{
26 2
		$h = floor($seconds / 60 / 60);
27 2
		$m = floor(($seconds - ($h * 60 * 60)) / 60);
28 2
		return self::timeToDecimal(sprintf('%02d:%02d:%02d', $h, $m, $seconds - ($h * 60 * 60) - ($m * 60)));
29
	}
30
31
	/**
32
	 * Convert elapsed time from "H:i:s" to decimal equivalent.
33
	 *
34
	 * @param string $time "12:00:00"
35
	 *
36
	 * @return float
37
	 */
38 2
	public static function timeToDecimal(string $time)
39
	{
40 2
		$hms = explode(':', $time);
41 2
		return $hms[0] + ($hms[1] / 60) + ($hms[2] / 3600);
42
	}
43
44
	/**
45
	 * Format elapsed time to short display value.
46
	 *
47
	 * @param float    $decTime     time in decimal format 1.5 = 1h 30m
48
	 * @param string   $type        hour text format 'short' or 'full'
49
	 * @param int|bool $withSeconds if is provided as int then will be displayed
50
	 *
51
	 * @return string
52
	 */
53 2
	public static function formatToHourText($decTime, $type = 'short', $withSeconds = false)
54
	{
55 2
		$short = $type === 'short';
56
57 2
		$hour = floor($decTime);
58 2
		$min = floor(($decTime - $hour) * 60);
59 2
		$sec = round((($decTime - $hour) * 60 - $min) * 60);
60
61 2
		$result = '';
62 2
		if ($hour) {
63
			$result .= $short ? $hour . \App\Language::translate('LBL_H') : "{$hour} " . \App\Language::translate('LBL_HOURS');
64
		}
65 2
		if ($hour || $min) {
66 1
			$result .= $short ? " {$min}" . \App\Language::translate('LBL_M') : " {$min} " . \App\Language::translate('LBL_MINUTES');
67
		}
68 2
		if ($withSeconds !== false) {
69 2
			$result .= $short ? " {$sec}" . \App\Language::translate('LBL_S') : " {$sec} " . \App\Language::translate('LBL_SECONDS');
70
		}
71 2
		if (!$hour && !$min && $withSeconds === false) {
72
			$result = $short ? '0' . \App\Language::translate('LBL_M') : '0 ' . \App\Language::translate('LBL_MINUTES');
73
		}
74 2
		return trim($result);
75
	}
76
}
77