-
Type: Epic
-
Resolution: Unresolved
-
Priority: Unknown
-
None
-
Affects Version/s: None
-
Component/s: None
-
None
-
To Do
-
PHPC enumerations
-
0
-
0
-
0
-
100
Before enumerations were introduced in PHP 8.1, many of our classes contained public constants for values. These values were used when instantiating the corresponding object. Consider the MongoDB\Driver\ReadPreference class:
$readPreference = new ReadPreference(ReadPreference::SECONDARY); // Uses a string constant $readPreference = new ReadPreference(ReadPreference::RP_SECONDARY); // Uses an int constant $readPreference = new ReadPreference('invalid'); // Raises an exception
This forces us to declare the parameters as int or string (or both in the case of ReadPreference), which also forces us to guard against unsupported values. Using enums would not necessarily simplify instantiation of those objects, but would greatly help static analysers point out invalid values:
enum ReadPreferenceMode: int { case Secondary = 1; // Imagine other modes being defined here } $readPreference = new ReadPreference(ReadPreferenceMode::Secondary); $readPreference = new ReadPreference('invalid'); // Type mismatch
An enum could be introduced for the following types:
- ReadPreference mode parameter
- WriteConcern w parameter (only case would be Majority to avoid people passing arbitrary strings), but the writeConcern constructor would always accept an int as well
- ReadConcern level parameter
- ClientEncryption encryption algorithms and query type
- Server types (can be reused for ServerDescription)
- Topology types
- Session Transaction states
- ServerApi versions
The introduction can be done in a backward compatible manner, especially considering that these enums would only be present in PHP >= 8.1. There are some accessors where we would not be able to introduce the enum values right away, e.g. ReadPreference::getMode() as those would be considered BC breaks.