Search code examples
phpjsonsymfonyrequestmapping

MapRequestPayload cannot acces information with hyphen


I have an app in Symfony 6.4 where I use attribute MapRequestPayload to parse incoming data. Until now it worked fine but I've started using external service (mailgun) to get some data and there is a problem mapping event-data varaible part. I cannot change the way data is sent to me. So everythime i want to use #[MapRequestPayload] data cannot have hypen in structure or it will not be mapped.

I recieve request with body:

{
   'signature': { ... },
   'event-data': { ... }

I'm trying to map it with #[MapRequestPayload] UpdateEmailStatusInput. Constructor I use in controller public function updateStatus(#[MapRequestPayload] UpdateEmailStatusInput $emailStatusInput)

class UpdateEmailStatusInput
{
    public function __construct(
        #[Assert\NotBlank] public array $signature,
        #[Assert\NotBlank] public array $eventData,
    ) {
    }
}

signature variable works fine, but eventData does not works (it is blank):

signature: array:3 []
eventData: null

I cannot make variable $event-data because PHP think it is #event (minus) const data.

Is ther some kind of config or workaraound to make it work out of the box? For the moment I'm using regural $request->getContent() to get the event-data variable.


Solution

  • Using SerializedName as sugessted resolved the issue. The whole structure is decoded, even names with hyphen deep in the structure.

    So Input class now look like this:

    use Symfony\Component\Validator\Constraints as Assert;
    use Symfony\Component\Serializer\Annotation\SerializedName;
    
    class UpdateEmailStatusInput
    {
        public function __construct(
            #[Assert\NotBlank]
            public array $signature,
            #[SerializedName('event-data')]
            #[Assert\NotBlank]
            public array $event,
        ) {
        }
    }
    

    and is called from controller: public function updateStatus(#[MapRequestPayload] UpdateEmailStatusInput $emailStatusInput)