Skip to content

Instantly share code, notes, and snippets.

@jehoshua02
Created May 22, 2023 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jehoshua02/e2b2390f6197b8dbf6ccc40b443e89ac to your computer and use it in GitHub Desktop.
Save jehoshua02/e2b2390f6197b8dbf6ccc40b443e89ac to your computer and use it in GitHub Desktop.
Quick recursive function to replace $refs in json schema.
<?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