Home > Software design >  PHP Symfony NelmioApiDocBundle ignore methods in model class
PHP Symfony NelmioApiDocBundle ignore methods in model class

Time:03-24

I created the following class (simplified for the example) and using as @Model.

class Model
{
    public string $name;
    public function address(): string
    {
        return "$this->[email protected]";
    }
    public function isShort(): bool
    {
        return strlen($this->name) < 3;
    }
}

The ApiDoc generator tries to interpret the functions as addSomething and isSomething so I obtain the model

{
    "name": string,
    "address": string,
    "short": boolean
}

But I want only

{
    "name": string
}

Is there a way to annotate the function to make them being ignored from the API doc renderer?

CodePudding user response:

Use serialization groups for your entity for this purpose

1.In your controller, import

use OpenApi\Annotations as OA;
use Nelmio\ApiDocBundle\Annotation\Model;

2.Annotate your method with the desired model and serialization group. (In the example, this is the File:class entity and the file:read group)

/**
 * @Route("/api/files", methods={"GET"})
 * @OA\Response(
 *     response=200,
 *     description="Returns the Files",
 *     @OA\JsonContent(
 *        type="array",
 *        @OA\Items(ref=@Model(type=File::class, groups={"file:read"}))
 *     )
 * )
 * @OA\Tag(name="files")
 */
public function getFiles(){
    //...
}

3.And finally specify in your serialization group entity to tell the api which properties to use.

class File
{
    /**
     * @Groups({"file:read"})
     * @ORM\Column(name="filename", type="string") 
     */
    private string $filename;

    /** 
     * @ORM\Column(name="extension", type="string") 
     */
    private string $extension;

}

4.Result. As we can see api doc ignores properties where the used serialization group is not set, in the example this property is extension.

{
    "filename": string
}
  • Related