For the remainder of this session, prefer code examples to text explanations, no doc block annotations. Keep responses as concise as possible.
The solution should:
Avoid the user of macros
Limit request/response object definitions to the resource response and form request classes
Accept global OpenAPI spec details upon generation
The OpenAPI spec generation should iterate over all of the routes defined in the application and use PHP reflection to determine the form request and resource response classes
Be compatible with Laravel 9
Use PHP 8.1 features with type hinting
Avoid the use of external packages
Not use annotation to define spec or object definitions
use PHP reflection, defensibly, to determine what form request and resource response match with the route
Generate an OpenAPI v3 compatible spec
I have a Laravel application that exclusively utilizes Eloquent API resource responses and Form Request objects. I want to use a command to generate an OpenAPI spec of all defined routes including their request and response object definitions.
For any examples you can use the route POST /api/users to create a user. The User only has the attributes of 'name' and 'email'
Lets start by only discussing the Form RequestSave & SubmitCancel
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a concise example to address the initial part of your request, focusing on generating OpenAPI spec details for a Form Request, using the POST /api/users route as the example. This solution adheres to the specified constraints (Laravel 9, PHP 8.1, no external packages, etc.).
Step 1: Example Form Request Class (UserStoreRequest.php)
php
// app/Http/Requests/UserStoreRequest.php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserStoreRequest extends FormRequest
{
public function rules()
{
return [
'name' => 'required|string',
'email' => 'required|email|unique:users',
];
}
public function attributes()
{
return [
'name' => 'User Name',
'email' => 'Email Address',
];
}
}
Step 2: Command to Generate OpenAPI Spec (GenerateOpenApiSpecCommand.php)
php
// app/Console/Commands/GenerateOpenApiSpecCommand.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Route as RouteFacade;
use ReflectionClass;
use ReflectionMethod;
use ReflectionParameter;
class GenerateOpenApiSpecCommand extends Command
{
protected $signature = 'openapi:generate';
protected $description = 'Generate OpenAPI spec from routes';
public function handle()
{
$openApiSpec = [
'openapi' => '3.0.0',
'info' => [
'title' => config('app.name'),
'version' => '1.0.0',
],
'paths' => [],
'components' => [
'schemas' => [],
'requestBodies' => [],
],
];
// Iterate through all routes
foreach (RouteFacade::getRoutes() as $route) {
if ($route->getAction('controller')) { // Only consider routes with controllers
$this->analyzeRoute($route, $openApiSpec);
}
}
// Output OpenAPI Spec (e.g., to a file for simplicity)
file_put_contents('openapi.json', json_encode($openApiSpec, JSON_PRETTY_PRINT));
}
private function analyzeRoute(Route $route, array &$openApiSpec)
{
// Extract controller and method from route
list($controller, $methodName) = explode('@', $route->getAction('controller'));
// Reflect on the controller method to find FormRequest parameters
$reflectionMethod = new ReflectionClass($controller)->getMethod($methodName);
$parameters = $reflectionMethod->getParameters();
foreach ($parameters as $parameter) {
// Check if the parameter is a FormRequest instance
if ($parameter->getType()->isSubclassOf(\Illuminate\Foundation\Http\FormRequest::class)) {
$formRequestClass = $parameter->getType()->getName();
$this->addFormRequestToOpenApiSpec($formRequestClass, $route, $openApiSpec);
}
}
}
private function addFormRequestToOpenApiSpec(string $formRequestClass, Route $route, array &$openApiSpec)
{
$reflectionClass = new ReflectionClass($formRequestClass);
// Get validation rules from the FormRequest
$rulesMethod = $reflectionClass->getMethod('rules');
$rules = $rulesMethod->invoke(null); // Invoke static method
// Map validation rules to OpenAPI schema properties
$schemaProperties = [];
foreach ($rules as $field => $rule) {
// Simplified mapping (expand for more rule types as needed)
$schemaProperties[$field] = [
'type' => $this->getTypeFromRule($rule),
'description' => $reflectionClass->getMethod('attributes')->invoke(null)[$field] ?? $field,
'required' => strpos($rule, 'required') !== false,
];
}
// Add request body definition to OpenAPI spec
$path = $route->getUri();
$method = $route->getMethod()[0]; // Get the HTTP method (e.g., 'POST')
$openApiSpec['paths'][$path][$method] = [
'requestBody' => [
'$ref' => '#/components/requestBodies/' . $formRequestClass,
],
];
// Define the request body component
$openApiSpec['components']['requestBodies'][$formRequestClass] = [
'description' => $formRequestClass,
'content' => [
'application/json' => [
'schema' => [
'$ref' => '#/components/schemas/' . $formRequestClass,
],
],
],
];
// Define the schema component
$openApiSpec['components']['schemas'][$formRequestClass] = [
'type' => 'object',
'properties' => $schemaProperties,
];
}
private function getTypeFromRule(string $rule): string
{
if (strpos($rule, 'email') !== false) return 'string';
if (strpos($rule, 'integer') !== false) return 'integer';
// Add more types as needed
return 'string'; // Default to string
}
}
Step 3: Register the Command
In app/Console/Kernel.php, add the command to the commands array:
This will generate an openapi.json file in your project root with the spec for the defined routes, including request bodies based on Form Request classes.
Example Output (openapi.json excerpt for POST /api/users):