api-platform / api-platform/core
Centralize Input/Output and Data Class Logic in Metadata
- Dominant language
- PHP
- Stars
- 2.6k
- Forks
- 980
- Avg merge
- 2d 5h
- Merged PRs (30d)
- 48
Description
Currently, across the codebase (e.g., in `ObjectMapperProvider`, `SerializerContextBuilder`, `OpenApiFactory`), we frequently encounter the pattern of checking for a custom input/output class and falling back to the resource class if not defined:
```php
$class = $operation->getInput()['class'] ?? $operation->getClass();
// or
$class = $operation->getOutput()['class'] ?? $operation->getClass();
```
To simplify the codebase and avoid repetitive logic, I propose introducing helper methods directly in the `Metadata` (and thus `Operation` and `ApiResource`) classes to handle these fallbacks.
#### Proposed Changes
The idea is to add the following methods:
1. **`getInputClass(): ?string`**: Returns the custom input class if defined, otherwise falls back to `getClass()`.
2. **`getOutputClass(): ?string`**: Returns the custom output class if defined, otherwise falls back to `getClass()`.
3. **`getDataClass(): ?string`**: (Optional/For discussion) A method to handle the mapped entity class with a similar fallback mechanism, specifically useful when working with DTOs and Data Mappers.
#### Benefits
- **Dry Code**: Centralizes the logic in one place.
- **Simplification**: Reduces boilerplate in providers, processors, and factories.
- **Consistency**: Ensures the fallback logic is applied identically everywhere.
#### Considerations
This changes metadata handling significantly. Cleaner API, but assess whether it requires a major (breaking) release or can remain optional.
Contributor guide
Assessment
This issue has not been assessed yet.