|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace MichaelRubel\Formatters\Collection; |
|
6
|
|
|
|
|
7
|
|
|
use Carbon\CarbonInterface; |
|
8
|
|
|
use Illuminate\Support\Carbon; |
|
9
|
|
|
use Illuminate\Support\Collection; |
|
10
|
|
|
use MichaelRubel\Formatters\Formatter; |
|
11
|
|
|
use MichaelRubel\Formatters\Traits\HelpsFormatData; |
|
12
|
|
|
|
|
13
|
|
|
class DateTimeFormatter implements Formatter |
|
14
|
|
|
{ |
|
15
|
|
|
use HelpsFormatData; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var string |
|
19
|
|
|
*/ |
|
20
|
|
|
public string $datetime_format = 'Y-m-d H:i'; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @var mixed |
|
24
|
|
|
*/ |
|
25
|
|
|
public mixed $instance; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @var mixed |
|
29
|
|
|
*/ |
|
30
|
|
|
public mixed $timezone; |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Format the date and time. |
|
34
|
|
|
* |
|
35
|
|
|
* @param Collection $items |
|
36
|
|
|
* |
|
37
|
|
|
* @return string |
|
38
|
|
|
*/ |
|
39
|
8 |
|
public function format(Collection $items): string |
|
40
|
|
|
{ |
|
41
|
8 |
|
if (! isset($this->instance)) { |
|
42
|
8 |
|
$this->getInstance($items); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
8 |
|
if (! isset($this->timezone)) { |
|
46
|
8 |
|
$this->setTimezone($items); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
8 |
|
if (! $this->instance instanceof CarbonInterface) { |
|
50
|
8 |
|
$this->instance = app(Carbon::class)->parse($this->instance); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
8 |
|
return $this->instance |
|
54
|
8 |
|
->setTimezone($this->timezone) |
|
55
|
8 |
|
->format($this->datetime_format); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @param Collection $items |
|
60
|
|
|
* |
|
61
|
|
|
* @return void |
|
62
|
|
|
*/ |
|
63
|
8 |
|
protected function getInstance(Collection $items): void |
|
64
|
|
|
{ |
|
65
|
8 |
|
$this->instance = $items->first(); |
|
66
|
|
|
|
|
67
|
8 |
|
if (is_array($this->instance)) { |
|
68
|
|
|
$this->instance = current($this->instance); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* @param Collection $items |
|
74
|
|
|
* |
|
75
|
|
|
* @return void |
|
76
|
|
|
*/ |
|
77
|
8 |
|
protected function setTimezone(Collection $items): void |
|
78
|
|
|
{ |
|
79
|
8 |
|
$this->timezone = config('app.timezone'); |
|
80
|
|
|
|
|
81
|
8 |
|
if (count($items) > 1) { |
|
82
|
1 |
|
$this->timezone = $items->last(); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|