yii2 icon indicating copy to clipboard operation
yii2 copied to clipboard

Support for backed Enums and DateTimes as query/action parameters

Open chriscpty opened this issue 2 months ago • 2 comments

As of current, controller action parameters can only have some built-in types (int, float, array etc.). Adding logic for \DateTime, \DateTimeImmutable and backed enums to the related logic in yii\base\Controller::bindActionParams should be easy; I'm willing to try implementing it myself.

chriscpty avatar Oct 14 '25 14:10 chriscpty

Great, we look forward to the PR.

terabytesoftw avatar Oct 14 '25 14:10 terabytesoftw

One problem I'm running into: If a parameter with a non-builtin type is missing from the query parameters, Yii2 tries to fill it using dependency injection (see yii\web\Controller::bindActionParams, line 165 and continuing).

This works fine at the moment because there's no overlap between types that can be posted as query parameters (built-in types) and types that can be set via DI (non-built-in types). So if a parameter is not in the query string, we always know whether to treat it as a missing query parameter (and set it to null or respond with 400 Bad Request) or as DI (and try to fill it via Yii2's DI logic).

In adding non-built-in types to the query parameters, there's an overlap now. So if I have an action method like public function actionFoo(\DateTime $bar) and the query string does not include bar, there's no way we could know if that parameter is just missing (=> we should respond with 400 Bad Request) or if $bar should be filled via DI (and throw a 500 Internal Server Error if there is nothing named bar in the DI container). Worse still, if $bar is nullable (public function actionFoo(?\DateTime $bar = null)), we don't know if we should just call the method with $bar = null or, again, try to fill it via DI.

I don't really see a solution for this, other than banning use of \DateTime or \BackedEnum in DI, which would be a pretty bad breaking change (I assume). Do you have ideas on how to solve this? Or am I missing something?

chriscpty avatar Oct 15 '25 13:10 chriscpty