Skip to content

Commit 818520c

Browse files
authored
PHPLIB-1040: Demonstrate enum handling in BSON tutorial (#1004)
1 parent b309cf8 commit 818520c

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

docs/tutorial/modeling-bson-data.txt

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,3 +156,60 @@ The same document in the MongoDB shell might display as:
156156
:php:`MongoDB\\BSON\\Persistable <mongodb-bson-persistable>` may only be used
157157
for root and embedded BSON documents. It may not be used for BSON arrays.
158158
.. _php-type-map:
159+
160+
Working with Enums
161+
------------------
162+
163+
:php:`Backed enums <enumerations.backed>` can be used with BSON and will
164+
serialize as their case value (i.e. integer or string).
165+
:php:`Pure enums <enumerations.basics>`, which have no backed cases, cannot be
166+
directly serialized. This is similar to how enums are handled by
167+
:php:`json_encode() <json-encode>`.
168+
169+
Round-tripping a backed enum through BSON requires special handling. In the
170+
following example, the `bsonUnserialize()` method in the class containing the
171+
enum is responsible for converting the value back to an enum case:
172+
173+
.. code-block:: php
174+
175+
<?php
176+
177+
enum Role: int
178+
{
179+
case USER = 1;
180+
case ADMIN = 2;
181+
}
182+
183+
class User implements MongoDB\BSON\Persistable
184+
{
185+
public function __construct(
186+
private string $username,
187+
private Role $role,
188+
private MongoDB\BSON\ObjectId $_id = new MongoDB\BSON\ObjectId(),
189+
) {}
190+
191+
public function bsonSerialize(): array
192+
{
193+
return [
194+
'_id' => $this->_id,
195+
'username' => $this->username,
196+
'role' => $this->role,
197+
];
198+
}
199+
200+
public function bsonUnserialize(array $data): void
201+
{
202+
$this->_id = $data['_id'];
203+
$this->username = $data['username'];
204+
$this->role = Role::from($data['role']);
205+
}
206+
}
207+
208+
Enums are prohibited from implementing
209+
:php:`MongoDB\\BSON\\Unserializable <mongodb-bson-unserializable>` and
210+
:php:`MongoDB\\BSON\\Persistable <mongodb-bson-persistable>`, since enum cases
211+
have no state and cannot be instantiated like ordinary objects. Pure and backed
212+
enums can, however, implement
213+
:php:`MongoDB\\BSON\\Serializable <mongodb-bson-serializable>`, which can be
214+
used to overcome the default behavior whereby backed enums are serialized as
215+
their case value and pure enums cannot be serialized.

0 commit comments

Comments
 (0)