Created
May 22, 2023 22:49
-
-
Save jehoshua02/e2b2390f6197b8dbf6ccc40b443e89ac to your computer and use it in GitHub Desktop.
Quick recursive function to replace $refs in json schema.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Libs; | |
class JsonSchema { | |
public static function flatten_spec($file) { | |
$path = dirname($file); | |
$json = static::load_json($file); | |
$contents = json_encode(static::replace_refs($path, $json)); | |
file_put_contents($path . '/openapi.json', $contents); | |
} | |
public static function replace_refs($path, $value) { | |
if (!is_array($value)) { | |
return $value; | |
} | |
if (isset($value['$ref'])) { | |
return static::evaluate_ref($path, $value); | |
} | |
return array_map(function ($v) use ($path) { | |
return static::replace_refs($path, $v); | |
}, $value); | |
} | |
public static function evaluate_ref($path, $value) { | |
echo "\nevaluating ref " . $path . '/' . $value['$ref']; | |
$file = realpath($path . '/' . $value['$ref']); | |
if (!file_exists($file)) { | |
echo "\nfile does not exist"; | |
return $value; | |
} | |
echo "\nfile exists"; | |
$json = static::load_json($file); | |
$path = dirname($file); | |
return static::replace_refs($path, $json); | |
} | |
public static function load_json($file) { | |
$contents = file_get_contents($file); | |
$json = json_decode($contents, true); | |
return $json; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment