mtrajano / laravel-swagger Goto Github PK
View Code? Open in Web Editor NEWAuto generates the swagger documentation of a laravel project based on best practices and simple assumptions
Auto generates the swagger documentation of a laravel project based on best practices and simple assumptions
First install says needs php 7.4 or higher but i have php8
i installed with --ignore-platform-req="mtrajano/laravel-swagger"
but when i try to generate i get the error below.
php artisan laravel-swagger:generate
ErrorException
Method ReflectionParameter::getClass() is deprecated
at vendor/mtrajano/laravel-swagger/src/Generator.php:193
189▕
190▕ $parameters = $action_instance->getParameters();
191▕
192▕ foreach ($parameters as $parameter) {
➜ 193▕ $class = $parameter->getClass();
194▕
195▕ if (!$class) {
196▕ continue;
197▕ }
+18 vendor frames
19 artisan:37
Illuminate\Foundation\Console\Kernel::handle()
What is wrong with this method does not exist ?
Do I have to provide it in all my controllers ?
Is there a config option to turn it off ?
Hello, I'm currently laravel-swagger to auto-generate my api endpoints. I want to filter only "API" endpoints will be create in the .json file. the code I've tried to run:
php artisan laravel-swagger:generate > public/swagger.json --filter="/api"
Its not working and returns NULL
{
"swagger": "2.0",
"info": {
"title": null,
"description": "",
"version": "1.0.0"
},
"host": null,
"basePath": "/",
"paths": []
}
image below is my api routes file
Say you have an internal session based API on /api
in your application, one would need to "log in" when running the command, especially if any of the validation rules use Auth::user()
.
A small local workaround by adding Auth::loginUsingId($userId)
to SwaggerServiceProvider->boot()
works, but is not very customizable. Would it be possible to add this as an auth option somehow?
composer require mtrajano/laravel-swagger
1/2: http://repo.packagist.org/p/provider-latest$0f8ef8716dcf883ffa6be62469aa0047043a1ca56377aa270d45090a0b3ac17e.json
2/2: http://repo.packagist.org/p/provider-2020-07$d81dbaf64d43d2489fabb975bfa8f9f16df42435286a2db9f5139e31e2a2e246.json
Finished: success: 2, skipped: 0, failure: 0, total: 2
Using version ^0.6.3 for mtrajano/laravel-swagger
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Conclusion: remove phpdocumentor/reflection-common 2.2.0
- Conclusion: don't install phpdocumentor/reflection-common 2.2.0
- phpdocumentor/reflection-docblock 4.3.0 requires phpdocumentor/reflection-common ^1.0.0 -> satisfiable by phpdocumentor/reflection-common[1.0, 1.0.1].
- phpdocumentor/reflection-docblock 4.3.1 requires phpdocumentor/reflection-common ^1.0.0 -> satisfiable by phpdocumentor/reflection-common[1.0, 1.0.1].
- Can only install one of: phpdocumentor/reflection-common[1.0, 2.2.0].
- Can only install one of: phpdocumentor/reflection-common[1.0.1, 2.2.0].
- Installation request for phpdocumentor/reflection-common (locked at 2.2.0) -> satisfiable by phpdocumentor/reflection-common[2.2.0].
- Installation request for mtrajano/laravel-swagger ^0.6.3 -> satisfiable by mtrajano/laravel-swagger[v0.6.3].
- Conclusion: don't install phpdocumentor/reflection-docblock 5.2.2|install phpdocumentor/reflection-docblock 4.3.0|install phpdocumentor/reflection-docblock 4.3.1
- Conclusion: remove phpdocumentor/reflection-docblock 5.2.2|install phpdocumentor/reflection-docblock 4.3.0|install phpdocumentor/reflection-docblock 4.3.1
- mtrajano/laravel-swagger v0.6.3 requires phpdocumentor/reflection-docblock ^4.3 -> satisfiable by phpdocumentor/reflection-docblock[4.3.0, 4.3.1, 4.3.2, 4.3.3, 4.3.4].
- Can only install one of: phpdocumentor/reflection-docblock[4.3.2, 5.2.2].
- Can only install one of: phpdocumentor/reflection-docblock[4.3.3, 5.2.2].
- Can only install one of: phpdocumentor/reflection-docblock[4.3.4, 5.2.2].
- Installation request for phpdocumentor/reflection-docblock (locked at 5.2.2) -> satisfiable by phpdocumentor/reflection-docblock[5.2.2].
Unable to install this package on fresh Laravel 8 installation, receiving the error mentioned above.
When I tried the filter option the console said it didn't exist, though it was in the readme. This tool is great by the way.
That is my question, works for lumen?
Thanks.
The Generator tries to call __toString()` on a ReflectionType which is deprecated since PHP7.1.
https://www.php.net/manual/en/reflectiontype.tostring.php
This means that you get an error when error reporting for deprecations is on.
php artisan laravel-swagger:generate
ErrorException : Function ReflectionType::__toString() is deprecated
at /var/www/html/vendor/mtrajano/laravel-swagger/src/Generator.php:156
152|
153| $parameters = $this->getActionClassInstance($this->action)->getParameters();
154|
155| foreach ($parameters as $parameter) {
> 156| $class = (string) $parameter->getType();
157|
158| if (is_subclass_of($class, FormRequest::class)) {
159| return (new $class)->rules();
160| }
Exception trace:
1 Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Function ReflectionType::__toString() is deprecated", "/var/www/html/vendor/mtrajano/laravel-swagger/src/Generator.php", [Object(ReflectionParameter)])
/var/www/html/vendor/mtrajano/laravel-swagger/src/Generator.php:156
2 Mtrajano\LaravelSwagger\Generator::getFormRules()
/var/www/html/vendor/mtrajano/laravel-swagger/src/Generator.php:134
When I attempt to run php artisan laravel-swagger:generate > swagger.json
I get the following error:
In Builder.php line 333:
No query results for model [App\Models\{MyModelNameHere}]
Any idea what might be causing this? The model is fully valid and used heavily in the application, the namespace is correct, as well.
When attempting to generate the docs for my API after switching to PHP 8 I get the following error:
In Generator.php line 193:
Method ReflectionParameter::getClass() is deprecated
After some quick digging I found this to help solve the issue: https://php.watch/versions/8.0/deprecated-reflectionparameter-methods
I tested the following code in that foreach
block which seems to do the trick:
foreach ($parameters as $parameter) {
$class_name = $name = $parameter->getType() && !$parameter->getType()->isBuiltin()
? new \ReflectionClass($parameter->getType()->getName())
: null;
if (is_subclass_of($class_name, FormRequest::class)) {
return (new $class_name)->rules();
}
}
when Form Request has a file value describe it using multipart form
change
php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"
to
php artisan vendor:publish --provider "Mtrajano\LaravelSwagger\SwaggerServiceProvider"
When API Resource exists to use it to generate a response.
Thanks for your great project.
When I run artisan laravel-swagger:generate
get this error. can you please help me to solve this?
I also ran compoer update
.
Laravel: 5.8
PHP: 7.3
Here is the full error:
Symfony\Component\Debug\Exception\FatalThrowableError : Argument 1 passed to Mtrajano\LaravelSwagger\Generator::getActionClassInstance() must be of the type string, object given, called in /var/www/isfahan-ahan.test/vendor/mtrajano/laravel-swagger/src/Generator.php on line 114
at /var/www/isfahan-ahan.test/vendor/mtrajano/laravel-swagger/src/Generator.php:177
173| return new Parameters\QueryParameterGenerator($rules);
174| }
175| }
176|
> 177| private function getActionClassInstance(string $action)
178| {
179| list($class, $method) = Str::parseCallback($action);
180|
181| return new ReflectionMethod($class, $method);
Exception trace:
1 Mtrajano\LaravelSwagger\Generator::getActionClassInstance(Object(Closure))
/var/www/isfahan-ahan.test/vendor/mtrajano/laravel-swagger/src/Generator.php:114
2 Mtrajano\LaravelSwagger\Generator::generatePath()
/var/www/isfahan-ahan.test/vendor/mtrajano/laravel-swagger/src/Generator.php:58
In my documentation what I created by hand I use definitions
like this:
/api/login:
post:
tags:
- login
summary: login into the API
description: |
You need to log in, receive a token, what you can use to the next steps
parameters:
- in: body
name: content
schema:
$ref: '#/definitions/credential'
responses:
200:
description: you are logged in
schema:
$ref: '#/definitions/token'
Here are the definitions to this above example:
definitions:
credential:
type: object
required:
- email
- password
properties:
email:
type: string
example: "[email protected]"
password:
type: string
example: "secret"
token:
type: object
properties:
token:
type: string
example: "JWT string"
It would be nice if the laravel-swagger could be generate this definitions because it's a very useful part of the API documentation when the frontend developers thinking about their models.
Even if i set in my config/laravel-swagger.php
'basePath' => '/api',
after running
php artisan laravel-swagger:generate --filter="/api/development_plans" > development_plans.json
the resulting file contains paths with /api included
Currently this package get all routes by calling default laravel router. Please add an ability to use custom class to get routes.
Typically we will need a new config that pass the default class to fetch all routes:
Currently:
$routes = app('Dingo\Api\Routing\Router')->getRoutes();
In this case I'm using package dingo/api so it should look like this:
$routes = [];
foreach(app('Dingo\Api\Routing\Router')->getRoutes() as $r) {
foreach($r->getRoutes() as $rr) {
$routes[] = $rr;
}
}
Anw, I believe this package would be a must-have package in future. Thanks so much for your efforts!
Hi there, I'm having a new project using the Laravel 6, and found a question for the feature that have been remove the global function of starts_with
please to consider about to upgrade it to using the helper class access such like Arr::class
and Str::class
, thanks.
at /var/www/integration.laravel/vendor/mtrajano/laravel-swagger/src/Generator.php:104
100| protected function getRouteUri(Route $route)
101| {
102| $uri = $route->uri();
103|
> 104| if (!starts_with($uri, '/')) {
105| $uri = '/' . $uri;
106| }
107|
108| return $uri;
Exception trace:
1 Mtrajano\LaravelSwagger\Generator::getRouteUri(Object(Illuminate\Routing\Route))
/var/www/integration.laravel/vendor/mtrajano/laravel-swagger/src/Generator.php:39
2 Mtrajano\LaravelSwagger\Generator::generate()
/var/www/integration.laravel/vendor/mtrajano/laravel-swagger/src/GenerateSwaggerDoc.php:34
Is there any way to define descriptions & examples in routes, models, controllers or rules?
I get this YAML output, what is excellent:
/api/member/user/create:
post:
description: POST /api/member/user/create
responses:
200:
description: OK
parameters:
- in: body
name: body
description: ""
schema:
type: object
required:
- lang_id
- name
- user
- password
- email
- is_inactive
properties:
lang_id:
type: integer
name:
type: string
user:
type: string
password:
type: string
email:
type: string
is_inactive:
type: boolean
But if I upgrade my code (routes, models, etc.) and regenerate this YAML file, all my modify gone. If I can define descriptions & examples between my code lines it can be prevent this issue and would be more handy.
Is this possible?
When you install debuger
public function __construct(string $middleware issue is signature if you change
namespace Mtrajano\LaravelSwagger\DataObjects;
class Middleware
{
private $name;
private $parameters;
public function __construct($middleware)
{
if (!is_string($middleware)) {
dd($middleware);
}
$tokens = explode(':', $middleware, 2);
$this->name = $tokens[0];
$this->parameters = isset($tokens[1]) ? explode(',', $tokens[1]) : [];
}
Closure($request, $next)^ {#2297
class: "Barryvdh\Debugbar\Controllers\BaseController"
this: Barryvdh\Debugbar\Controllers\OpenHandlerController {#2296 …}
file: "./vendor/barryvdh/laravel-debugbar/src/Controllers/BaseController.php"
line: "25 to 30"
}
and what is caousing issue
<?php
namespace Barryvdh\Debugbar\Controllers;
use Barryvdh\Debugbar\LaravelDebugbar;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Laravel\Telescope\Telescope;
// phpcs:ignoreFile
if (class_exists('Illuminate\Routing\Controller')) {
class BaseController extends Controller
{
protected $debugbar;
public function __construct(Request $request, LaravelDebugbar $debugbar)
{
$this->debugbar = $debugbar;
if ($request->hasSession()) {
$request->session()->reflash();
}
**$this->middleware(function ($request, $next) {**
if (class_exists(Telescope::class)) {
Telescope::stopRecording();
}
return $next($request);
});
}
}
When I try to install with the follow command:
composer require mtrajano/laravel-swagger
I get the follow error:
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Conclusion: remove phpdocumentor/reflection-common 2.0.0
- Conclusion: don't install phpdocumentor/reflection-common 2.0.0
- phpdocumentor/reflection-docblock 4.3.0 requires phpdocumentor/reflection-common ^1.0.0 -> satisfiable by phpdocumentor/reflection-common[1.0, 1.0.1].
- phpdocumentor/reflection-docblock 4.3.1 requires phpdocumentor/reflection-common ^1.0.0 -> satisfiable by phpdocumentor/reflection-common[1.0, 1.0.1].
- Can only install one of: phpdocumentor/reflection-common[1.0, 2.0.0].
- Can only install one of: phpdocumentor/reflection-common[1.0.1, 2.0.0].
- Installation request for phpdocumentor/reflection-common (locked at 2.0.0) -> satisfiable by phpdocumentor/reflection-common[2.0.0].
- Installation request for mtrajano/laravel-swagger ^0.6.3 -> satisfiable by mtrajano/laravel-swagger[v0.6.3].
- Conclusion: don't install phpdocumentor/reflection-docblock 5.0.0|install phpdocumentor/reflection-docblock 4.3.0|install phpdocumentor/reflection-docblock 4.3.1
- Conclusion: remove phpdocumentor/reflection-docblock 5.0.0|install phpdocumentor/reflection-docblock 4.3.0|install phpdocumentor/reflection-docblock 4.3.1
- mtrajano/laravel-swagger v0.6.3 requires phpdocumentor/reflection-docblock ^4.3 -> satisfiable by phpdocumentor/reflection-docblock[4.3.0, 4.3.1, 4.3.2, 4.3.3, 4.3.4].
- Can only install one of: phpdocumentor/reflection-docblock[4.3.2, 5.0.0].
- Can only install one of: phpdocumentor/reflection-docblock[4.3.3, 5.0.0].
- Can only install one of: phpdocumentor/reflection-docblock[4.3.4, 5.0.0].
- Installation request for phpdocumentor/reflection-docblock (locked at 5.0.0) -> satisfiable by phpdocumentor/reflection-docblock[5.0.0].
How to fix that?
Thanks.
seems like generator doesn't parse Requests,
I called controller and request class like in your sample, but haven't got params in JSON file
Does somebody test it ?
also will you implement generation samples of response using laravel resource classes?
Hi, me again. hahaha, have some problem here,
some api needs to passing token, and for now, the generated document structural have't been support yet, have u consider to implement this issue by reading the middleware?
Route::group(['middleware' => ['auth:admin','jwt.auth']], function ($router) {
// and the following route document will add the input block to fill token
// to recognized authenticate route, can add a suffix to the title ' - (token required) '
})
After all, in order to persist the route nicely read, the less work to optimize the document can adding a artisan command option --sort
, so the related api will generate together.
thanks !
After I run the script, I get the following
"/archive/color/add": {
"post": {
"summary": "",
"description": "",
"deprecated": false,
"responses": {
"200": {
"description": "OK"
}
},
"parameters": [
{
"in": "body",
"name": "body",
"description": "",
"schema": {
"type": "object",
"required": [
"color_name",
"color_en_name",
"archive_status"
],
"properties": {
"color_name": {
"type": "string"
},
"color_en_name": {
"type": "string"
},
"color_value": {
"type": "string"
},
"color_remark": {
"type": "string"
},
"archive_status": {
"type": "string",
"enum": [
"enable",
"disable"
]
}
}
}
}
]
}
}
There is no parameter description and return value description.The result waht I want is like this:
"\/archive\/color\/add": {
"post": {
"summary": "",
"description": "",
"deprecated": false,
"responses": {
"200": {
"description": "OK",
"schema": {
"$schema": "http:\/\/json-schema.org\/draft-04\/schema#",
"type": "object",
"properties": {
"code": {
"type": "numeric",
"description": "description string",
"required": true
},
"msg": {
"type": "string",
"description": "description string",
"required": true
}
}
}
}
},
"parameters": [
{
"in": "body",
"name": "body",
"description": "",
"schema": {
"type": "object",
"required": [
"color_name",
"color_en_name",
"archive_status"
],
"properties": {
"color_name": {
"type": "string",
"description": "description string",
},
"color_en_name": {
"type": "string",
"description": "description string",
},
"color_value": {
"type": "string",
"description": "description string",
},
"color_remark": {
"type": "string",
"description": "description string",
},
"archive_status": {
"type": "string",
"description": "description string",
"enum": [
"enable",
"disable"
]
}
}
}
}
]
}
}
How can i do it?
Is there any possibility to support swagger generator for Dingo API Routes (php artisan api:routes
).
references:
dingo/api
: https://github.com/dingo/apicomposer require mtrajano/laravel-swagger
Problem 1
- Conclusion: remove phpdocumentor/reflection-common 2.0.0
- Conclusion: don't install phpdocumentor/reflection-common 2.0.0
- phpdocumentor/reflection-docblock 4.3.0 requires phpdocumentor/reflection-common ^1.0.0 -> satisfiable by phpdocumentor/reflection-common[1.0, 1.0.1].
- phpdocumentor/reflection-docblock 4.3.1 requires phpdocumentor/reflection-common ^1.0.0 -> satisfiable by phpdocumentor/reflection-common[1.0, 1.0.1].
- Can only install one of: phpdocumentor/reflection-common[1.0, 2.0.0].
- Can only install one of: phpdocumentor/reflection-common[1.0.1, 2.0.0].
- Installation request for phpdocumentor/reflection-common (locked at 2.0.0) -> satisfiable by phpdocumentor/reflection-common[2.0.0].
- Installation request for mtrajano/laravel-swagger ^0.6.3 -> satisfiable by mtrajano/laravel-swagger[v0.6.3].
- Conclusion: don't install phpdocumentor/reflection-docblock 5.1.0|install phpdocumentor/reflection-docblock 4.3.0|install phpdocumentor/reflection-docblock 4.3.1
- Conclusion: remove phpdocumentor/reflection-docblock 5.1.0|install phpdocumentor/reflection-docblock 4.3.0|install phpdocumentor/reflection-docblock 4.3.1
- mtrajano/laravel-swagger v0.6.3 requires phpdocumentor/reflection-docblock ^4.3 -> satisfiable by phpdocumentor/reflection-docblock[4.3.0, 4.3.1, 4.3.2, 4.3.3, 4.3.4].
- Can only install one of: phpdocumentor/reflection-docblock[4.3.2, 5.1.0].
- Can only install one of: phpdocumentor/reflection-docblock[4.3.3, 5.1.0].
- Can only install one of: phpdocumentor/reflection-docblock[4.3.4, 5.1.0].
- Installation request for phpdocumentor/reflection-docblock (locked at 5.1.0) -> satisfiable by phpdocumentor/reflection-docblock[5.1.0].
It seems that the --filter option is broken. I am getting an error: "The "--filter" option does not exist" after running -
php artisan laravel-swagger:generate --filter="/ads"
I tried with and without surrounding quotes.
Hello,
I like the feature of automatically generating request structure from the request parameters in Laravel routes. But I am not able to generate response structure. Is there any configuration for this?
eg:
public function login(LoginRequest $request) { // some code return response()->json([ 'access_token' => $accessToken, 'token_type' => 'Bearer', 'scopes' => $scopes, 'expires_at' => $tokenResult->token->expires_at->timestamp ]) }
This call is generating
"responses": { "200": { "description": "OK" } },
But how can I generate the actual response structure? It would be very helpful because then I can use this json to generate code for my Angular front end.
when we use arrays validation, in "Example Value" it will generate null value for that parameter.
Hello,
Right now, the Generator checks if a specific route has a Passport middleware on the route definition only.
https://github.com/mtrajano/laravel-swagger/blob/master/src/Generator.php#L173
Middlewares can also be defined on the Controllers. I think that the Generator should also scan them to get additionally defined middlewares.
Example:
// Route
Route::get('/something', MyController::class);
// Controller
class MyController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
}
}
// If we call
app('App\Http\Controllers\API\MyController')->getMiddleware()
// returns
[
[
"middleware" => "auth:api",
"options" => [],
],
]
If you agree I can work on a PR that adds this functionality.
Thank you,
Hi,
Is --filter removed in 0.7 by design. ?
Small feedback or usage case:
My project is small laravel project that uses nova and sanctum, not pasport:
I had to disable oauth in config, since i do not use passport but sanctum.
Since sanctum is new defacto package for SPA and Mobile APP (simple ones), it would be nice to look in to this. I can't promise but if time allows i will try to create PR.
and btw great work !!!
Thank you for such a wonderful package. It's been a life-saver!
I would like to suggest the addition of --output="/path/file.json"
option. It would greatly assist in creating a custom command to trigger the auto-generation. Currently, calling
php artisan laravel-swagger:generate > storage/api-docs/api-docs.json --filter="/api"
inside another command generates an error (either due to the >
), hence, the --output
option would really come in handy.
maybe add some new parameter for phpdoc in controller, that allow group operations by tag
If there is a route with PATCH method an error will be thrown: Undefined index: patch
Fixed it in SuccessResponseGenerator.php:
$methodMappingHttpCode = [
'head' => 200,
'get' => 200,
'post' => 201,
'put' => 204,
'delete' => 204,
'patch' => 204,
];
Another issue when I'm using laravel-debugbar in src/DataObjects/Route.php
line #78 since middleware constructor only accept string, so I had to hack it like this
protected function formatMiddleware()
{
return array_map(function ($middleware) {
if (gettype($middleware) !== 'string') {
// dd($middleware);
return new Middleware('ignored');
}
return new Middleware((string)$middleware);
}, $this->route->gatherMiddleware());
}
Tried to dump the $middleware object then I got:
^ Closure($request, $next)^ {#1346
class: "Barryvdh\Debugbar\Controllers\BaseController"
this: Barryvdh\Debugbar\Controllers\OpenHandlerController {#1345 …}
}
Another issue again:
Is this package dependant to laravel-passport? Tried to disable parseSecurity
to false but it was still required. I had to install laravel-passport and configure it to make this package working
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.