Passed
Push — main ( f366b1...10819c )
by Michael
05:46 queued 01:56
created

DateTimeFormatter::setTimezone()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
rs 10
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
68
    /**
69
     * @param Collection $items
70
     *
71
     * @return void
72
     */
73 8
    protected function setTimezone(Collection $items): void
74
    {
75 8
        $this->timezone = config('app.timezone');
76
77 8
        if (count($items) > 1) {
78 1
            $this->timezone = $items->last();
79
        }
80
    }
81
}
82