Skip to content

Comments

Constants as openapi const union type#1095

Closed
apasquini95 wants to merge 9 commits intodedoc:mainfrom
apasquini95:constants-as-openapi-const-union-type
Closed

Constants as openapi const union type#1095
apasquini95 wants to merge 9 commits intodedoc:mainfrom
apasquini95:constants-as-openapi-const-union-type

Conversation

@apasquini95
Copy link
Contributor

Hi everyone, I'm opening this PR as an enhancement of the previous one (#1086). I introduced the const schema also when handling union types, but only if the literal has only one value.

Union type with single literal value:

class MyController {
  const MY_CONST = "my_const";

  public function index(bool $param): string|MyDto
  {
    return $param ? self::MY_CONST : new MyDto;
  }
}
anyOf:
    - { $ref: '#/components/schemas/MyDto' }
    - { type: string, const: 'my_const' }

Union type with more than one literal value:

class MyController {
  const MY_CONST = "my_const";
  const MY_OTHER_CONST = "my_other_const";

  public function index(bool $param1, bool $param2): string|MyDto
  {
    return $param1 
      ? self::MY_CONST 
      : ($param2
        ? self::MY_OTHER_CONST
        : new MyDto);
  }
}
anyOf:
    - { $ref: '#/components/schemas/MyDto' }
    - { type: string, enum: ['my_const', 'my_other_const'] }

I decided to leave the enum schema when there are more than one literal of the same type just to avoid having a much longer result and keep its readability.

anyOf:
    - { $ref: '#/components/schemas/MyDto' }
    - { type: string, const: 'my_const' }
    - { type: string, const: 'my_other_const' }

@romalytvynenko
Copy link
Member

@apasquini95 thanks for the pr, but this is not something I want to be a default behavior.

If you need this for your projects, consider using a document transformer and manually patch schemas there (there is an open api object traverser that can be handy for this task).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants