Passed
Push — master ( 62919d...1f65fa )
by Iman
04:23
created

Time::timeAgo()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 16
nop 3
dl 0
loc 21
rs 8.9617
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->d -= floor($diff->d / 7) * 7;
24
25
        foreach ($this->string as $k => &$v) {
26
            if ($diff->$k) {
27
                $v = $diff->$k.' '.$v.($diff->$k > 1 ? 's' : '');
28
            } else {
29
                unset($this->string[$k]);
30
            }
31
        }
32
33
        if (! $full) {
34
            $this->string = array_slice($this->string, 0, 1);
35
        }
36
37
        return $this->string ? implode(', ', $this->string).' ' : 'just now';
38
    }
39
40
    /**
41
     * @param $datetime_from
42
     * @return \DateTime
43
     */
44
    private function getNow($datetime_from)
45
    {
46
        $datetime_from = ($datetime_from) ?: YmdHis();
47
        $now = new \DateTime;
48
        if ($datetime_from != '') {
49
            $now = new \DateTime($datetime_from);
50
        }
51
52
        return $now;
53
    }
54
}