Conditions | 22 |
Paths | 55 |
Total Lines | 71 |
Code Lines | 47 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
18 | function smarty_modifier_relativedate($input) |
||
19 | { |
||
20 | $now = new DateTime(); |
||
21 | |||
22 | if (gettype($input) === 'object' |
||
23 | && (get_class($input) === DateTime::class || get_class($input) === DateTimeImmutable::class) |
||
24 | ) { |
||
25 | $then = $input; |
||
26 | } |
||
27 | else { |
||
28 | try { |
||
29 | $then = new DateTime($input); |
||
30 | } |
||
31 | catch (Exception $ex) { |
||
32 | return $input; |
||
33 | } |
||
34 | } |
||
35 | |||
36 | $secs = $now->getTimestamp() - $then->getTimestamp(); |
||
37 | |||
38 | $second = 1; |
||
39 | $minute = 60 * $second; |
||
40 | $minuteCut = 60 * $second; |
||
41 | $hour = 60 * $minute; |
||
42 | $hourCut = 90 * $minute; |
||
43 | $day = 24 * $hour; |
||
44 | $dayCut = 48 * $hour; |
||
45 | $week = 7 * $day; |
||
46 | $weekCut = 14 * $day; |
||
47 | $month = 30 * $day; |
||
48 | $monthCut = 60 * $day; |
||
49 | $year = 365 * $day; |
||
50 | $yearCut = $year * 2; |
||
51 | |||
52 | $pluralise = true; |
||
53 | |||
54 | if ($secs <= 10) { |
||
55 | $output = "just now"; |
||
56 | $pluralise = false; |
||
57 | } |
||
58 | elseif ($secs > 10 && $secs < $minuteCut) { |
||
59 | $output = round($secs / $second) . " second"; |
||
60 | } |
||
61 | elseif ($secs >= $minuteCut && $secs < $hourCut) { |
||
62 | $output = round($secs / $minute) . " minute"; |
||
63 | } |
||
64 | elseif ($secs >= $hourCut && $secs < $dayCut) { |
||
65 | $output = round($secs / $hour) . " hour"; |
||
66 | } |
||
67 | elseif ($secs >= $dayCut && $secs < $weekCut) { |
||
68 | $output = round($secs / $day) . " day"; |
||
69 | } |
||
70 | elseif ($secs >= $weekCut && $secs < $monthCut) { |
||
71 | $output = round($secs / $week) . " week"; |
||
72 | } |
||
73 | elseif ($secs >= $monthCut && $secs < $yearCut) { |
||
74 | $output = round($secs / $month) . " month"; |
||
75 | } |
||
76 | elseif ($secs >= $yearCut && $secs < $year * 10) { |
||
77 | $output = round($secs / $year) . " year"; |
||
78 | } |
||
79 | else { |
||
80 | $output = "a long time ago"; |
||
81 | $pluralise = false; |
||
82 | } |
||
83 | |||
84 | if ($pluralise) { |
||
85 | $output = (substr($output, 0, 2) <> "1 ") ? $output . "s ago" : $output . " ago"; |
||
86 | } |
||
87 | |||
88 | return $output; |
||
89 | } |
||
90 |