FriendsOfSymfony / FOSRestBundle

This Bundle provides various tools to rapidly develop RESTful API's with Symfony
http://symfony.com/doc/master/bundles/FOSRestBundle/index.html
MIT License
2.79k stars 704 forks source link

ParamFetcherListener Mapping the value as array works differently #2279

Open ko2in opened 3 years ago

ko2in commented 3 years ago

According to the documentation, when mapping the value as array, the param fetcher will validate each entries of array with the requirements and replace with default value if each entry is invalid.

* @QueryParam(map=true, name="ids", requirements="\d+", default="1", description="List of ids")
* If you want to map the value as an array (apply the requirements to each element): ie. ?ids[]=1&ids[]=2&ids[]=1337.
* (works with QueryParam and RequestParam)
*
* It will validate each entries of ids with your requirement, by this way, if an entry is invalid,
* this one will be replaced by default value.
*
* ie: ?ids[]=1337&ids[]=notinteger will return array(1337, 1);

But, it replaces the whole array with the default value (1) as string.

The documentation says: If ids is not defined, array(1) will be given, but it returns the default value as string (1).

Here's the test results with my REST client. FOS

Below is my sample code in controller:

/**
     * Create a new post
     *
     * @FOS\Post("/post", name="create_post")
     * @FOS\RequestParam(name="title", nullable=true)
     * @FOS\RequestParam(name="content", nullable=true)
     * @FOS\RequestParam(name="categories", nullable=true)
     * @FOS\QueryParam(map=true, name="ids", requirements="\d+", default="1", description="List of ids")
     */
    public function createPost(ParamFetcher $paramFetcher)
    {
        echo $paramFetcher->get('title') . "\r\n";
        echo $paramFetcher->get('content') . "\r\n";
        print_r($paramFetcher->get('categories'));
        print_r($paramFetcher->get('ids'));
        die();
    }
GuilhemN commented 3 years ago

This was the case in 1.x but we refactored the param fetcher in 2.0 and the default value is not longer type casted to array since. I think the issue here is that the docs are outdated, PR welcome if you'd like to fix them :)

I believe this decision was taken to allow default values with a different type. You can fix your code with:


    /**
     * @FOS\QueryParam(map=true, name="ids", requirements="\d+", default=["1"], description="List of ids")
     */