Debian Codegraph @

vendor/ipl/html/src/FormElement/LocalDateTimeElement.php

raw
1 <?php
2
3 namespace ipl\Html\FormElement;
4
5 use DateTime;
6 use ipl\Validator\DateTimeValidator;
7 use ipl\Validator\ValidatorChain;
8
9 class LocalDateTimeElement extends InputElement
10 {
11 public const FORMAT = 'Y-m-d\TH:i:s';
12
13 protected $type = 'datetime-local';
14
15 protected $defaultAttributes = ['step' => '1'];
16
17 /** @var DateTime */
18 protected $value;
19
20 public function setValue($value)
21 {
22 if (is_string($value)) {
23 $originalVal = $value;
24 $value = DateTime::createFromFormat(static::FORMAT, $value);
25 // In Chrome, if the seconds are set to 00, DateTime::createFromFormat() returns false.
26 // Create DateTime without seconds in format
27 if ($value === false) {
28 $format = substr(static::FORMAT, 0, strrpos(static::FORMAT, ':') ?: null);
29 $value = DateTime::createFromFormat($format, $originalVal);
30 }
31
32 if ($value === false) {
33 $value = $originalVal;
34 }
35 }
36
37 return parent::setValue($value);
38 }
39
40 public function getValueAttribute()
41 {
42 if (! $this->value instanceof DateTime) {
43 return $this->value;
44 }
45
46 return $this->value->format(static::FORMAT);
47 }
48
49 protected function addDefaultValidators(ValidatorChain $chain): void
50 {
51 $chain->add(new DateTimeValidator());
52 }
53 }