Completed
Push — master ( e0cc8e...b29470 )
by f
01:20
created

TimeUnitSpeller::spellInterval()   C

Complexity

Conditions 8
Paths 21

Size

Total Lines 33
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
nc 21
dl 0
loc 33
c 0
b 0
f 0
cc 8
eloc 25
nop 2
rs 5.3846
1
<?php
2
namespace morphos;
3
4
use DateInterval;
5
6
abstract class TimeUnitSpeller
7
{
8
	const YEAR = 'year';
9
	const MONTH = 'month';
10
	const DAY = 'day';
11
	const HOUR = 'hour';
12
	const MINUTE = 'minute';
13
	const SECOND = 'second';
14
15
	const AGO = 'ago';
16
	const IN = 'in';
17
18
	const AND = 'and';
19
20
	const JUST_NOW = 'just now';
21
22
	const DIRECTION = 1;
23
	const SEPARATE = 2;
24
25
	abstract public static function spellUnit($count, $unit);
26
27
	public static function spellInterval(DateInterval $interval, $options = 0)
28
	{
29
		$parts = [];
30
		foreach ([
31
			'y' => self::YEAR,
32
			'm' => self::MONTH,
33
			'd' => self::DAY,
34
			'h' => self::HOUR,
35
			'i' => self::MINUTE,
36
			's' => self::SECOND
37
		] as $interval_field => $unit) {
38
			if ($interval->{$interval_field} > 0)
39
				$parts[] = static::spellUnit($interval->{$interval_field}, $unit);
40
		}
41
42
		if (empty($parts))
43
			return static::JUST_NOW;
44
45
		if ($options & self::SEPARATE && count($parts) > 1) {
46
			$last_part = array_pop($parts);
47
			$spelled = implode(', ', $parts).' '.static::AND.' '.$last_part;
48
		} else
49
			$spelled = implode(' ', $parts);
50
51
		if ($options & self::DIRECTION) {
52
			if ($interval->invert)
53
				$spelled = static::IN.' '.$spelled;
54
			else
55
				$spelled .= ' '.static::AGO;
56
		}
57
58
		return $spelled;
59
	}
60
}
61