Completed
Push — master ( 1c26be...19bb2d )
by Basil
05:42
created

DurationValue::getValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
1
<?php
2
3
namespace luya\web\jsonld;
4
5
/**
6
 * Convert Timestamp or String to duration.
7
 * 
8
 * Example usage:
9
 * 
10
 * ```php
11
 * new DurationValue(strtotime("1 hour 30 minutes", 0));
12
 * ```
13
 * 
14
 * Or as string
15
 * 
16
 * ```php
17
 * new DurationValue("1 hour 30 minutes");
18
 * ```
19
 * 
20
 * @see https://stackoverflow.com/a/13301472/4611030
21
 * 
22
 * @author Basil Suter <[email protected]>
23
 * @since 1.0.3
24
 */
25
class DurationValue extends BaseValue
26
{
27
    private $_duration;
28
    
29
    public function __construct($duration)
30
    {
31
        $this->_duration = $duration;    
32
    }
33
    
34
    public function getValue()
35
    {
36
        // if its not a unix timestamp, try to convert "strtotime("1 hour 30 minutes", 0);"
37
        if (!is_numeric($this->_duration)) {
38
            $this->_duration = strtotime($this->_duration, 0);   
39
        }
40
        
41
        return $this->timeToIso8601Duration($this->_duration);
42
    }
43
    
44
    protected function timeToIso8601Duration($time)
45
    {
46
        $units = array(
47
            "Y" => 365*24*3600,
48
            "D" =>     24*3600,
49
            "H" =>        3600,
50
            "M" =>          60,
51
            "S" =>           1,
52
        );
53
        
54
        $str = "P";
55
        $istime = false;
56
        
57
        foreach ($units as $unitName => &$unit) {
58
            $quot  = intval($time / $unit);
59
            $time -= $quot * $unit;
60
            $unit  = $quot;
61
            if ($unit > 0) {
62
                if (!$istime && in_array($unitName, array("H", "M", "S"))) { // There may be a better way to do this
63
                    $str .= "T";
64
                    $istime = true;
65
                }
66
                $str .= strval($unit) . $unitName;
67
            }
68
        }
69
        
70
        return $str;
71
    }
72
}