I have a symfony API endpoint that goes like this:
/orders/list-all?since=2024-10-21
I’d like to map that query string parameter to a DateTimeImmutable (or DateTimeInterface), like so:
public function listOrders(
#[OAQueryParameter(name: 'since', in: 'query', description: 'Date de début de la recherche', required: false, schema: new OASchema(type: 'string', format: 'date'))]
#[MapQueryParameter()]
?DateTimeInterface $since = null
): Response
But this doesn’t seems to work.
I’ve looked at :
- DateTimeValueResolver
- MapDateTime (that would allow me to specify the date format)
But I don’t get how they are supposed to work, and the documentation is very light on that matter.
By reading and debugging though the DateTimeValueResolver source code, I’ve seen that $request->attributes->has($argument->getName())
is always false.
Is there any example usage out there ?
2
Answers
You cannot use
MapQueryParameter
with types other thanarray
,string
,int
,float
,bool
orBackedEnum
.What you can do is to accept
since
as type string and then create aDateTimeImmutable
afterward.The
MapDateTime
takes the data from$request->attributes
and not from$request->query
, where thesince
parameter is in.So for now, I think you need to stick with the above mentioned logic.
In addition to answer above, you can solve this issue by using the
#[MapQueryString]
and mapping your parameters into a DTO. This could prove useful if you plan on adding more parameters to filter by. Here is a minimal example of what I mean:Controller:
DTO:
You can also add the OpenAPI annotations or Validator validation into your DTO. I also provide the output produced for this solution in screenshots from Postman:
Without params:
With
$from
param:Good thing is, that you can combine
#[MapQueryString]
attributes into different DTOs. Good example may be pagination of the list:Sample request: