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

Time   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 48
rs 10
c 0
b 0
f 0
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
B timeAgo() 0 21 6
A getNow() 0 9 3
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
}