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

DateFormatter::getInstance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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
12
class DateFormatter implements Formatter
13
{
14
    /**
15
     * @var string
16
     */
17
    public string $date_format = 'Y-m-d';
18
19
    /**
20
     * @var mixed
21
     */
22
    public mixed $instance;
23
24
    /**
25
     * @var mixed
26
     */
27
    public mixed $timezone;
28
29
    /**
30
     * Format the date.
31
     *
32
     * @param Collection $items
33
     *
34
     * @return string
35
     */
36 7
    public function format(Collection $items): string
37
    {
38 7
        if (! isset($this->instance)) {
39 7
            $this->getInstance($items);
40
        }
41
42 7
        if (! isset($this->timezone)) {
43 7
            $this->getTimezone($items);
44
        }
45
46 7
        if (! $this->instance instanceof CarbonInterface) {
47 7
            $this->instance = app(Carbon::class)->parse($this->instance);
48
        }
49
50 7
        return $this->instance
51 7
            ->setTimezone($this->timezone)
52 7
            ->format($this->date_format);
53
    }
54
55
    /**
56
     * @param Collection $items
57
     *
58
     * @return void
59
     */
60 7
    protected function getInstance(Collection $items): void
61
    {
62 7
        $this->instance = $items->first();
63
    }
64
65
    /**
66
     * @param Collection $items
67
     *
68
     * @return void
69
     */
70 7
    protected function getTimezone(Collection $items): void
71
    {
72 7
        $this->timezone = config('app.timezone');
73
74 7
        if (count($items) > 1) {
75 1
            $this->timezone = $items->last();
76
        }
77
    }
78
}
79