LoginSignup
12
4

More than 5 years have passed since last update.

Laravelでartisan使ってSwagger.jsonを出力する

Last updated at Posted at 2017-08-10

経緯

Laravel使ったAPIサーバーを立てていて、ドキュメント化はSwagger使っているのですが、Swagger.jsonを吐き出すコマンドを毎回コピペしてていい加減発狂しそうだったのでartisanコマンド作ろうと思いました。

前提

Laravel5.4

作ってみる

  1. コマンドを作成する

    shell
    $ php artisan make:command SwaggerOutput
    

    こんな感じで出来上がります。

    app/
    ├── Console
    │   ├── Commands
    │   │   └── SwaggerOutput.php
    
  2. SwaggerOutputに実行するコマンドを実装する

    app/Console/Commands/SwaggerOutPut.php
    <?php
    
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    
    class SwaggerOutput extends Command
    {
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'swagger:output';
    
        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'vendor/bin/swagger app -o public/swagger を実行する';
    
        /**
         * swagger output
         *
         * @return mixed
         */
        public function handle()
        {
            $this->info(shell_exec("vendor/bin/swagger app -o public/swagger"));
        }
    }
    

    vendor/bin/swagger app -o public/swagger はいつも使っているものに置き換えて下さい。

  3. Kernel.phpに追加する

    app/Console/Kernel.php
    protected $commands = [
        Commands\SwaggerOutput::class
    ];
    
  4. 実行する

    shell
    $ php artisan swagger:output
    

    いつものコマンドと同様に実行結果が出力されます。

    Swagger-PHP 2.0.9
    -----------------
        get /api/test
       post /api/test
     delete /api/test
      patch /api/test
    ------------------------
    4 operations documented
    ------------------------
    Written to /var/www/html/public/swagger/swagger.json
    

さいごに

コマンド忘れても php artisan list ですぐに見れるのでPHPUnitとかよく使うコマンドは全部artisanコマンドに統合していきたいなと思いました。

12
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
4