-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenApiSpecLoader.php
More file actions
104 lines (83 loc) · 2.59 KB
/
OpenApiSpecLoader.php
File metadata and controls
104 lines (83 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
declare(strict_types=1);
namespace Studio\OpenApiContractTesting;
use const JSON_THROW_ON_ERROR;
use RuntimeException;
use function file_exists;
use function file_get_contents;
use function json_decode;
use function rtrim;
final class OpenApiSpecLoader
{
private static ?string $basePath = null;
/** @var string[] */
private static array $stripPrefixes = [];
/** @var array<string, array<string, mixed>> */
private static array $cache = [];
/**
* Configure the spec loader with a base path and optional strip prefixes.
*
* @param string[] $stripPrefixes
*/
public static function configure(string $basePath, array $stripPrefixes = []): void
{
self::$basePath = rtrim($basePath, '/');
self::$stripPrefixes = $stripPrefixes;
}
public static function getBasePath(): string
{
if (self::$basePath === null) {
throw new RuntimeException(
'OpenApiSpecLoader base path not configured. '
. 'Call OpenApiSpecLoader::configure() or set spec_base_path in PHPUnit extension parameters.',
);
}
return self::$basePath;
}
/** @return string[] */
public static function getStripPrefixes(): array
{
return self::$stripPrefixes;
}
/** @return array<string, mixed> */
public static function load(string $specName): array
{
if (isset(self::$cache[$specName])) {
return self::$cache[$specName];
}
$path = self::getBasePath() . "/{$specName}.json";
if (!file_exists($path)) {
throw new RuntimeException(
"OpenAPI bundled spec not found: {$path}. Run 'cd openapi && npm run bundle' first.",
);
}
$content = file_get_contents($path);
if ($content === false) {
throw new RuntimeException("Failed to read OpenAPI spec: {$path}");
}
/** @var array<string, mixed> $decoded */
$decoded = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
self::$cache[$specName] = $decoded;
return $decoded;
}
/**
* Clear only the cached specs, keeping basePath and stripPrefixes intact.
*/
public static function clearCache(): void
{
self::$cache = [];
}
/**
* Remove a single spec from the cache.
*/
public static function evict(string $specName): void
{
unset(self::$cache[$specName]);
}
public static function reset(): void
{
self::$basePath = null;
self::$stripPrefixes = [];
self::$cache = [];
}
}