Passed
Pull Request — main (#14)
by Michael
03:29
created

DateTimeFormatter::__construct()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 15
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.0466

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 6
c 3
b 0
f 0
nc 8
nop 3
dl 0
loc 15
ccs 6
cts 7
cp 0.8571
crap 4.0466
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 MichaelRubel\Formatters\Formatter;
10
11
class DateTimeFormatter implements Formatter
12
{
13
    /**
14
     * @param  string|null|CarbonInterface  $datetime
15
     * @param  string|null  $timezone
16
     * @param  string|null  $datetime_format
17
     */
18 12
    public function __construct(
19
        public string|null|CarbonInterface $datetime = null,
20
        public string|null $timezone = null,
21
        public string|null $datetime_format = 'Y-m-d H:i',
22
    ) {
23 12
        if (! $this->timezone) {
24 9
            $this->timezone = config('app.timezone', 'UTC');
25
        }
26
27 12
        if (! $this->datetime instanceof CarbonInterface) {
28 7
            $this->datetime = app(Carbon::class)->parse($this->datetime);
29
        }
30
31 12
        if (! $this->datetime_format) {
32
            $this->datetime_format = 'Y-m-d H:i';
33
        }
34
    }
35
36
    /**
37
     * Format the date and time.
38
     *
39
     * @return string
40
     */
41 12
    public function format(): string
42
    {
43 12
        return $this->datetime
44 12
            ->setTimezone($this->timezone)
0 ignored issues
show
Bug introduced by
The method setTimezone() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

44
            ->/** @scrutinizer ignore-call */ setTimezone($this->timezone)

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
45 12
            ->translatedFormat($this->datetime_format);
0 ignored issues
show
Bug introduced by
It seems like $this->datetime_format can also be of type null; however, parameter $format of Carbon\CarbonInterface::translatedFormat() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

45
            ->translatedFormat(/** @scrutinizer ignore-type */ $this->datetime_format);
Loading history...
46
    }
47
}
48