Search code examples
phpsymfonyvalidationfosrestbundle

FOSRestBundle Queryparam return value if not passed


I have a controller with many methods to which I pass get parameters. And I expect to receive some data in response (depending on the params I pass). I am trying to use symphony's @QueryParam to validate the incoming values as some of them are necessary.

There may be more than 1 parameter passed but the first one, sponsorId, is necessary and if its not passed I want to return something like 'ERROR: id is not set'

currently I am not using @QueryParam and I use something like this:

public function getSponsorById(Request $request)
{
  if(!$args['sponsorId']) {
     return 'ERROR: id is not set';
  }

  .....
  $sponsor = .....
  return $sponsor;
}

It is simple, I just return error message if I don't get the parameter. but how do I make it work with @QueryParam ? How do I say it to return a certain value if it fails the validation?

/**
 * @QueryParam(name="sponsorId", default="", strict=true)
 */
public function getSponsorById(Request $request)
{
  .....
  $sponsor = .....
  return $sponsor;
}

Solution

  • In this case you can do it manually by using symfony ParamFetcher class.

    In your controller input argument add ParamFetcher $paramFetcher:

    use FOS\RestBundle\Request\ParamFetcher;
    
    ...
    
    /**
     * @QueryParam(name="sponsorId", default="", strict=true)
     */
    public function getSponsorById(Request $request, ParamFetcher $paramFetcher)
    {
      $sponsorId = $paramFetcher->get('sponsorId');
    
      // Logic to validate $sponsorId and give it default value if not valid.
    }
    

    Also you can use requirements and nullable parameters with any php regex pattern that validate your input and give error if not valid. like this:

    use FOS\RestBundle\Request\ParamFetcher;
    
    ...
    
    /**
     * @QueryParam(name="sponsorId", nullable=true, default="", requirements="\d+", strict=true)
     */
    public function getSponsorById(Request $request, ParamFetcher $paramFetcher)
    {
      $sponsorId = $paramFetcher->get('sponsorId');
      // Your code.
    }
    

    If strict set as true, when regex not matched to input, RestBundle thrown an error and if strict was false, when regex not matched to input, parameter just skipped.