summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/html/src/FormElement/LocalDateTimeElement.php
blob: a628b57b86b7648ae06dddca3a514d40b3e08d90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php

namespace ipl\Html\FormElement;

use DateTime;
use ipl\Validator\DateTimeValidator;
use ipl\Validator\ValidatorChain;

class LocalDateTimeElement extends InputElement
{
    public const FORMAT = 'Y-m-d\TH:i:s';

    protected $type = 'datetime-local';

    protected $defaultAttributes = ['step' => '1'];

    /** @var DateTime */
    protected $value;

    public function setValue($value)
    {
        if (is_string($value)) {
            $originalVal = $value;
            $value = DateTime::createFromFormat(static::FORMAT, $value);
            // In Chrome, if the seconds are set to 00, DateTime::createFromFormat() returns false.
            // Create DateTime without seconds in format
            if ($value === false) {
                $format = substr(static::FORMAT, 0, strrpos(static::FORMAT, ':') ?: null);
                $value = DateTime::createFromFormat($format, $originalVal);
            }

            if ($value === false) {
                $value = $originalVal;
            }
        }

        return parent::setValue($value);
    }

    public function getValueAttribute()
    {
        if (! $this->value instanceof DateTime) {
            return $this->value;
        }

        return $this->value->format(static::FORMAT);
    }

    protected function addDefaultValidators(ValidatorChain $chain): void
    {
        $chain->add(new DateTimeValidator());
    }
}