Skip to content

Update "Custom Mapping Types" documentation for a fully working example #2778

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions docs/en/reference/custom-mapping-types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ a ``DateTimeImmutable`` when the data is read from the database.
use Doctrine\ODM\MongoDB\Types\ClosureToPHP;
use Doctrine\ODM\MongoDB\Types\Type;
use MongoDB\BSON\UTCDateTime;
use RuntimeException;

class DateTimeWithTimezoneType extends Type
{
Expand All @@ -33,6 +34,10 @@ a ``DateTimeImmutable`` when the data is read from the database.

public function convertToPHPValue($value): DateTimeImmutable
{
if (!isset($value['utc'], $value['tz'])) {
throw new RuntimeException('Database value cannot be converted to date with timezone. Expected array with "utc" and "tz" keys.');
}

$timeZone = new DateTimeZone($value['tz']);
$dateTime = $value['utc']
->toDateTime()
Expand All @@ -43,8 +48,13 @@ a ``DateTimeImmutable`` when the data is read from the database.

public function convertToDatabaseValue($value): array
{
if (! isset($value['utc'], $value['tz'])) {
throw new RuntimeException('Database value cannot be converted to date with timezone. Expected array with "utc" and "tz" keys.');
if (!$value instanceof DateTimeImmutable) {
throw new \RuntimeException(
sprintf(
'Expected instance of \DateTimeImmutable, got %s',
gettype($value)
)
);
}

return [
Expand Down