Passed
Push — main ( ebbc7c...eb1d9a )
by Michael
04:10
created

DateFormatter   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Test Coverage

Coverage 94.44%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
dl 0
loc 68
ccs 17
cts 18
cp 0.9444
rs 10
c 1
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 17 4
A getTimezone() 0 6 2
A getInstance() 0 6 2
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 7
        if (is_array($this->instance)) {
65
            $this->instance = current($this->instance);
66
        }
67
    }
68
69
    /**
70
     * @param Collection $items
71
     *
72
     * @return void
73
     */
74 7
    protected function getTimezone(Collection $items): void
75
    {
76 7
        $this->timezone = config('app.timezone');
77
78 7
        if (count($items) > 1) {
79 1
            $this->timezone = $items->last();
80
        }
81
    }
82
}
83