Passed
Push — master ( c52d76...a99d60 )
by Iman
09:00 queued 04:52
created

Time::timeAgo()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 13
nc 16
nop 3
dl 0
loc 22
rs 8.6737
c 0
b 0
f 0
1
<?php
2
3
namespace crocodicstudio\crudbooster\helpers;
4
5
class Time
6
{
7
    private $string = [
8
        'y' => 'year',
9
        'm' => 'month',
10
        'w' => 'week',
11
        'd' => 'day',
12
        'h' => 'hour',
13
        'i' => 'minute',
14
        's' => 'second',
15
    ];
16
17
    public function timeAgo($datetime_to, $datetime_from = null, $full = false)
18
    {
19
        $now = $this->getNow($datetime_from);
20
        $ago = new \DateTime($datetime_to);
21
        $diff = $now->diff($ago);
22
23
        $diff->w = floor($diff->d / 7);
0 ignored issues
show
Bug introduced by
The property w does not seem to exist on DateInterval.
Loading history...
24
        $diff->d -= $diff->w * 7;
25
26
        foreach ($this->string as $k => &$v) {
27
            if ($diff->$k) {
28
                $v = $diff->$k.' '.$v.($diff->$k > 1 ? 's' : '');
29
            } else {
30
                unset($this->string[$k]);
31
            }
32
        }
33
34
        if (! $full) {
35
            $this->string = array_slice($this->string, 0, 1);
36
        }
37
38
        return $this->string ? implode(', ', $this->string).' ' : 'just now';
39
    }
40
41
    /**
42
     * @param $datetime_from
43
     * @return \DateTime
44
     */
45
    private function getNow($datetime_from)
46
    {
47
        $datetime_from = ($datetime_from) ?: date('Y-m-d H:i:s');
48
        $now = new \DateTime;
49
        if ($datetime_from != '') {
50
            $now = new \DateTime($datetime_from);
51
        }
52
53
        return $now;
54
    }
55
}