Skip to content

Commit

Permalink
DateInput: supports DateTimeImmutable
Browse files Browse the repository at this point in the history
  • Loading branch information
MartkCz committed Jan 30, 2024
1 parent c408b37 commit 7f427c9
Showing 1 changed file with 29 additions and 7 deletions.
36 changes: 29 additions & 7 deletions src/DateInput.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
namespace WebChemistry\Controls;

use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use LogicException;
use Nette;
use Nette\Forms\Controls\TextInput;
use Nette\Forms\Validator;
Expand All @@ -28,12 +31,20 @@ final class DateInput extends TextInput {
/** @var int */
private $type = self::DATE;

private $immutable = false;

public function __construct($label = null, int $maxLength = null) {
parent::__construct($label, $maxLength);

$this->setHtmlType('date');
}

public function setImmutable($immutable = true) {
$this->immutable = $immutable;

return $this;
}

public function setDateTime() {
$this->setHtmlType('datetime-local');
$this->type = self::DATETIME;
Expand Down Expand Up @@ -62,9 +73,13 @@ protected function getHttpData($type, ?string $htmlTail = null) {
try {
$date = null;
if ($str) {
$date = new \DateTime($str);
if (!$this->immutable) {
$date = new DateTime($str);
} else {
$date = new DateTimeImmutable($str);
}
}
} catch (\Throwable $e) {
} catch (Throwable $e) {
$msg = Validator::$messages[self::DATE_VALID] ?? 'Date is not correct.';

$this->addError($msg);
Expand Down Expand Up @@ -99,24 +114,31 @@ public function getControl(): Nette\Utils\Html {
public function setValue($value) {
if (is_string($value)) {
try {
$value = new DateTime($value);
if (!$this->immutable) {
$value = new DateTime($value);
} else {
$value = new DateTimeImmutable($value);
}
} catch (Throwable $exception) {
throw new \LogicException(
throw new LogicException(
sprintf('Cannot create datetime from string, %s given.', $value),
0,
$exception
);
}
} else if ($value !== null && !$value instanceof DateTime) {
throw new \LogicException("Must be a string or DateTime or null.");
} else if ($value !== null && !$value instanceof DateTimeInterface) {
throw new LogicException("Must be a string or DateTime or DateTimeImmutable or null.");
}

$this->value = $value;

return $this;
}

public function getValue(): ?DateTime {
/**
* @return DateTime|DateTimeImmutable|null
*/
public function getValue() {
return $this->value;
}

Expand Down

0 comments on commit 7f427c9

Please sign in to comment.