Search code examples
phpannotationsswaggerswagger-codegen

How to produce a model with a custom Datetime annotation using swagger codegen


We have a requirement to annotate a datetime field with the following annotation:

@Type("DateTime<'Y-m-d\TH:i:sP'>")

Can someone advice how to achieve this using swagger code gen. Codebase is PHP. Current field definition is as follows:

created:
        type: "string"
        format: "date-time"
        description: "Date client details first appeared in the system."         
        default: null

Required output:

/**
     * Date client details first appeared in the system.
     *
     * @var \DateTime|null
     * @SerializedName("createdDate")
     * @Assert\DateTime()
     * @Type("DateTime<'Y-m-d\TH:i:sP'>")
     */
    protected $createdDate;

What is being produced by swagger codegen:

 /**
     * Date client details first appeared in the system.
     *
     * @var \DateTime|null
     * @SerializedName("createdDate")
     * @Assert\DateTime()
     * @Type("DateTime")
     */
    protected $createdDate;

Solution

  • Swagger Codegen uses Mustache templates to generate the code. For example, the PHP annotations from your example are defined in this template:

    https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen/src/main/resources/php-symfony/model_variables.mustache

    You can modify these templates to customize the output.


    Download the template above to your computer and change the date-time annotations as required. Then run the codegen using the -t argument to specify the path to your custom templates:

    java -jar swagger-codegen-cli-2.4.4.jar generate
      -i http://petstore.swagger.io/v2/swagger.json
      -l php-symfony
      -o petstore_php_server
      -t path/to/MyTemplates    <------
    

    Any custom templates found in the -t folder will be used instead of the corresponding standard templates. Templates not found in the -t folder will default to the standard templates.