1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Benrowe\Formatter\Providers; |
4
|
|
|
|
5
|
|
|
use Benrowe\Formatter\AbstractFormatterProvider; |
6
|
|
|
use Carbon\Carbon; |
7
|
|
|
use Carbon\CarbonInterval; |
8
|
|
|
|
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* DateTime Formatter |
12
|
|
|
* |
13
|
|
|
* Contains formatter for datetime values |
14
|
|
|
* |
15
|
|
|
* @package Benrowe\Formatter |
16
|
|
|
*/ |
17
|
|
|
class DateTime extends AbstractFormatterProvider |
18
|
|
|
{ |
19
|
1 |
|
public function asDate($value, $format = 'Y-m-d') |
|
|
|
|
20
|
|
|
{ |
21
|
1 |
|
return $this->output($value, $format); |
22
|
|
|
} |
23
|
|
|
|
24
|
1 |
|
public function asTime($value, $format = 'H:i:s') |
|
|
|
|
25
|
|
|
{ |
26
|
1 |
|
return $this->output($value, $format); |
27
|
|
|
} |
28
|
|
|
|
29
|
1 |
|
public function asDateTime($value, $format = 'Y-m-d H:i:s') |
|
|
|
|
30
|
|
|
{ |
31
|
1 |
|
return $this->output($value, $format); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Take in a number of seconds and display that as a human readable amount of time |
36
|
|
|
* |
37
|
|
|
* @param int $value |
38
|
|
|
* @return string |
|
|
|
|
39
|
|
|
*/ |
40
|
|
|
public function asHuman($value) |
41
|
|
|
{ |
42
|
|
|
$int = CarbonInterval::seconds($value); |
|
|
|
|
43
|
|
|
} |
44
|
|
|
|
45
|
3 |
|
private function output($value, $format) |
|
|
|
|
46
|
|
|
{ |
47
|
3 |
|
return $this |
48
|
3 |
|
->normaliseValue($value) |
49
|
3 |
|
->format($format); |
50
|
|
|
} |
51
|
|
|
|
52
|
3 |
|
private function normaliseValue($value) |
53
|
|
|
{ |
54
|
3 |
|
$carbon = $this->getCarbon(); |
55
|
|
|
// sniff the value type |
56
|
3 |
|
if (is_int($value)) { |
57
|
3 |
|
return $carbon->createFromTimestamp($value); |
58
|
|
|
} |
59
|
|
|
return $carbon->parse($value); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Get an instance of the carbon datetime handler |
64
|
|
|
* |
65
|
|
|
* @return Carbon |
66
|
|
|
*/ |
67
|
3 |
|
private function getCarbon() |
68
|
|
|
{ |
69
|
3 |
|
if (!class_exists('Carbon\Carbon')) { |
70
|
|
|
throw new FormatterException( |
71
|
|
|
'Unable to load the nesbot/carbon dependency.' |
72
|
|
|
); |
73
|
|
|
} |
74
|
3 |
|
return new Carbon; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@return
annotation as described here.