Skip to content

Commit

Permalink
Cast date/time/datetime values to DateTimeImmutable
Browse files Browse the repository at this point in the history
  • Loading branch information
szymach committed Mar 12, 2019
1 parent 620ede1 commit 6620356
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
24 changes: 21 additions & 3 deletions Model/Resource.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

namespace FSi\Bundle\ResourceRepositoryBundle\Model;

use DateTime;
use DateTimeImmutable;
use DateTimeInterface;

class Resource implements ResourceValue
{
Expand Down Expand Up @@ -82,7 +84,7 @@ public function getTextValue()

public function setDateValue($dateValue)
{
$this->dateValue = $dateValue;
$this->dateValue = $this->toDateTimeImmutable($dateValue);
}

public function getDateValue()
Expand All @@ -92,7 +94,7 @@ public function getDateValue()

public function setDatetimeValue($datetimeValue)
{
$this->datetimeValue = $datetimeValue;
$this->datetimeValue = $this->toDateTimeImmutable($datetimeValue);
}

public function getDatetimeValue()
Expand All @@ -102,7 +104,7 @@ public function getDatetimeValue()

public function setTimeValue($timeValue)
{
$this->timeValue = $timeValue;
$this->timeValue = $this->toDateTimeImmutable($timeValue);
}

public function getTimeValue()
Expand Down Expand Up @@ -139,4 +141,20 @@ public function getBoolValue()
{
return $this->boolValue;
}

/**
* Symfony date/time/datetime forms do not allow for default DateTimeImmutable
* value until version 4.2, so the values need to be casted manually.
*
* @param DateTimeInterface|null $value
* @return DateTimeImmutable|null
*/
private function toDateTimeImmutable(?DateTimeInterface $value): ?DateTimeImmutable
{
if (true === $value instanceof DateTime) {
$value = DateTimeImmutable::createFromMutable($value);
}

return $value;
}
}
2 changes: 1 addition & 1 deletion Model/ResourceValue.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

namespace FSi\Bundle\ResourceRepositoryBundle\Model;

Interface ResourceValue
interface ResourceValue
{
/**
* @param string $key
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"fsi/doctrine-extensions-bundle": "^1.0|^2.0",
"fsi/form-extensions-bundle": "^2.0",
"phpunit/phpunit": "^7.1",
"phpspec/phpspec": "^4.3",
"phpspec/phpspec": "^5.0",
"phpspec/prophecy": "^1.7",
"sebastian/exporter": "^3.1.0"
},
Expand Down

0 comments on commit 6620356

Please sign in to comment.