Passed
Push — master ( a733b3...61ba41 )
by Derek Stephen
09:40
created

DateTransformer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 0
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Del\Form\Field\Transformer;
6
7
use DateTime;
8
use DateTimeInterface;
9
use DateTimeZone;
10
use Del\Form\Field\TransformerInterface;
11
12
class DateTransformer implements TransformerInterface
13
{
14
    public function __construct(
15
        private string $dateFormat
16
    ) {}
17
18
    public function input(mixed $data): string
19
    {
20
        if ($data instanceof DateTimeInterface) {
21
            return $data->format('Y-m-d');
22
        }
23
24
        return $data !== null ? $data : '';
25
    }
26
27
    public function output(string $value): ?DateTimeInterface
28
    {
29
        $date =  DateTime::createFromFormat($this->dateFormat, $value, new DateTimeZone('UTC'));
30
31
        if (!$date) {
0 ignored issues
show
introduced by
$date is of type DateTime, thus it always evaluated to true.
Loading history...
32
            $date = new DateTime($value, new DateTimeZone('UTC'));
33
        }
34
35
        return $date ?: null;
0 ignored issues
show
introduced by
$date is of type DateTime, thus it always evaluated to true.
Loading history...
36
    }
37
}
38