Skip to content

Instantly share code, notes, and snippets.

@mrmuminov
Last active July 13, 2023 19:45
Show Gist options
  • Save mrmuminov/ac0317f4fe75469c37f6b0a747fbb3e3 to your computer and use it in GitHub Desktop.
Save mrmuminov/ac0317f4fe75469c37f6b0a747fbb3e3 to your computer and use it in GitHub Desktop.
PHP swagger. Generic response

Parent (Base, Main) response schema

#[OA\Schema]
class BaseResponse {
    #[OA\Property]
    public ?string $message = null;
    #[OA\Property(type: 'object')]
    public mixed $result = null;     
}

Child response schema

#[OA\Schema]
class ChildResponse {
    #[OA\Property]
    public int $id;
    #[OA\Property]
    public string $name;     
}

Action

use OpenApi\Attributes as OA;

#[OA\Get(
    path: '/v1/some-path',
    description: "Generics",
)]
#[OA\Response(
    response: 200,
    description: "Success",
    content: new OA\JsonContent(
        allOf: [
            new OA\Schema(ref: '#/components/schemas/BaseResponse'),
            new OA\Schema(
                properties: [
                    new OA\Property(
                        property: 'result',
                        type: 'array',
                        items: new OA\Items(
                            allOf: [
                                new OA\Schema(ref: "#/components/schemas/ChildResponse"),
                            ]
                        ),
                    )
                ]
            ),
        ]
    )
)]
class GetReferencesAction {}

Result

{
  "message": "string",
  "result": [
    {
      "id": 0,
      "name": "string"
    }
  ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment