LoginSignup
2
2

More than 3 years have passed since last update.

Stoplight Studioで作成したswagger.yamlを並び替えて見やすくするプログラムを作った

Last updated at Posted at 2020-09-13

Swagger.yamlを作るのにstoplightのツールはとても便利なのですが、
生成されるファイルは、ツールで登録した順に記述されるので、後でSwagger.yamlそのものを、見た時に並び順がバラバラで見づらくなります。
そこで、APIやComponentを昇順に並び替えて、中の項目も同じ順で並び替えるプログラムを作りました。

事前準備

yamlファイルの読み込み、書き出しにsymfony/yamlパッケージを使います。
composerを使ってインストールしてください。

例:

composer.json
{
    "require": {
        "symfony/yaml": "*"
    }
}

php composer install

使い方

以下のプログラムを、整形したいswaggerファイルを指定して実行するだけです。
指定したファイルの拡張子の手前に、_convertedとついたファイルが生成されます。

convert_swagger.php
<?php
require 'vendor/autoload.php';
use Symfony\Component\Yaml\Yaml;

// yamlファイルを読み込んでarray配列に変換する
$file_name = $argv[1];
$content = file_get_contents($file_name);
$yaml_array = Yaml::parse($content);

// APIの並びをURLの昇順にする
$paths = $yaml_array["paths"];
ksort($paths);
$yaml_array["paths"] = $paths;

// components schemasの並び順を昇順にする
$schemas = [];
if(array_key_exists("components", $yaml_array)){
    $schemas = $yaml_array["components"]["schemas"];
    ksort($schemas);
}

// APIの項目を並び替える
foreach($paths as $key1 => $value1){
    foreach($value1 as $key2 => $value2){
        $item = [];
        $item["operationId"] = $value2["operationId"];
        if(array_key_exists("tags", $value2)){
            $item["tags"] = $value2["tags"];
        }
        $item["summary"] = $value2["summary"];
        $item["description"] = $value2["description"];
        $item["parameters"] = $value2["parameters"];
        if(array_key_exists("requestBody", $value2)){
            $item["requestBody"] = $value2["requestBody"];
        }
        $item["responses"] = $value2["responses"];
        $yaml_array["paths"][$key1][$key2] = $item;
    }
}

// components schemasの項目を並び替える
foreach($schemas as $key => $value){
    $item = [];
    $item["title"] = $value["title"];
    $item["description"] = $value["description"];
    $item["type"] = $value["type"];
    $item["properties"] = $value["properties"];
    if(array_key_exists("required", $value)){
        $item["required"] = $value["required"];
    }
    $yaml_array["components"]["schemas"][$key] = $item;
}

// 並び替えたデータをyaml形式に変換し、ファイルに出力する
$file_name = preg_replace("/\.yaml$/", "_converted.yaml", $file_name);
file_put_contents($file_name, Yaml::dump($yaml_array,99,2));
?>

実行例
php convert_swagger.php sample.v1.yaml
sample.v1_converted.yamlが生成されます。

2
2
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
2
2