|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Maiorano\Shortcodes\Library; |
|
4
|
|
|
|
|
5
|
|
|
use DateInterval; |
|
6
|
|
|
use DateTime; |
|
7
|
|
|
use Exception; |
|
8
|
|
|
use Maiorano\Shortcodes\Contracts\AttributeInterface; |
|
9
|
|
|
use Maiorano\Shortcodes\Contracts\Traits\Attribute; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Calculates the age of something |
|
13
|
|
|
* Usage: [age units=years]September 19th 1984[/age]. |
|
14
|
|
|
*/ |
|
15
|
|
|
final class Age implements AttributeInterface |
|
16
|
|
|
{ |
|
17
|
|
|
use Attribute; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var string |
|
21
|
|
|
*/ |
|
22
|
|
|
protected $name = 'age'; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var mixed[] |
|
26
|
|
|
*/ |
|
27
|
|
|
protected $attributes = ['units' => 'years']; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @param string|null $content |
|
31
|
|
|
* @param mixed[] $atts |
|
32
|
|
|
* |
|
33
|
|
|
* @throws Exception |
|
34
|
|
|
* |
|
35
|
|
|
* @return string |
|
36
|
|
|
*/ |
|
37
|
9 |
|
public function handle(string $content = null, array $atts = []): string |
|
38
|
|
|
{ |
|
39
|
9 |
|
if (!$content) { |
|
40
|
1 |
|
return ''; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
8 |
|
$now = new DateTime('now'); |
|
44
|
8 |
|
$birthday = new DateTime($content); |
|
45
|
8 |
|
$v = $this->calculate($atts['units'], $now->diff($birthday)); |
|
|
|
|
|
|
46
|
|
|
|
|
47
|
8 |
|
return sprintf('%d %s', $v, $atts['units']); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* @param string $units |
|
52
|
|
|
* @param DateInterval $diff |
|
53
|
|
|
* |
|
54
|
|
|
* @return mixed |
|
55
|
|
|
*/ |
|
56
|
8 |
|
private function calculate($units, DateInterval $diff) |
|
57
|
|
|
{ |
|
58
|
|
|
$calculator = [ |
|
59
|
|
|
'centuries' => function (DateInterval $diff) { |
|
60
|
1 |
|
return $diff->y / 100; |
|
61
|
8 |
|
}, |
|
62
|
|
|
'decades' => function (DateInterval $diff) { |
|
63
|
1 |
|
return $diff->y / 10; |
|
64
|
8 |
|
}, |
|
65
|
|
|
'years' => function (DateInterval $diff) { |
|
66
|
1 |
|
return $diff->y; |
|
67
|
8 |
|
}, |
|
68
|
|
|
'months' => function (DateInterval $diff) { |
|
69
|
1 |
|
return $diff->y * 12 + $diff->m; |
|
70
|
8 |
|
}, |
|
71
|
|
|
'days' => function (DateInterval $diff) { |
|
72
|
1 |
|
return $diff->days; |
|
73
|
8 |
|
}, |
|
74
|
|
|
'hours' => function (DateInterval $diff) { |
|
75
|
1 |
|
return ($diff->days * 24) + $diff->h; |
|
76
|
8 |
|
}, |
|
77
|
|
|
'minutes' => function (DateInterval $diff) { |
|
78
|
1 |
|
return ($diff->days * 24 * 60) + $diff->i; |
|
79
|
8 |
|
}, |
|
80
|
|
|
'seconds' => function (DateInterval $diff) { |
|
81
|
1 |
|
return ($diff->days * 24 * 60 * 60) + $diff->s; |
|
82
|
8 |
|
}, |
|
83
|
|
|
]; |
|
84
|
8 |
|
$u = isset($calculator[$units]) ? $units : 'years'; |
|
85
|
|
|
|
|
86
|
8 |
|
return $calculator[$u]($diff); |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|