-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScenarioRepository.php
More file actions
95 lines (72 loc) · 2.46 KB
/
Copy pathScenarioRepository.php
File metadata and controls
95 lines (72 loc) · 2.46 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
<?php
declare(strict_types=1);
namespace Greph\Tests\Oracle;
use Greph\Support\Json;
final readonly class ScenarioRepository
{
public function __construct(private string $rootPath)
{
}
public function get(string $name): Scenario
{
$path = $this->rootPath . '/scenarios/' . $name . '/scenario.json';
if (!is_file($path)) {
throw new \InvalidArgumentException(sprintf('Unknown scenario: %s', $name));
}
return new Scenario($name, $this->rootPath, $this->loadDefinition($path));
}
/**
* @return list<Scenario>
*/
public function all(): array
{
$root = $this->rootPath . '/scenarios';
if (!is_dir($root)) {
return [];
}
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($root, \FilesystemIterator::SKIP_DOTS)
);
$scenarios = [];
foreach ($iterator as $fileInfo) {
if (!$fileInfo instanceof \SplFileInfo || $fileInfo->getFilename() !== 'scenario.json') {
continue;
}
$relativeName = substr($fileInfo->getPathname(), strlen($root) + 1, -strlen('/scenario.json'));
if ($relativeName === '') {
continue;
}
$scenarios[] = new Scenario($relativeName, $this->rootPath, $this->loadDefinition($fileInfo->getPathname()));
}
usort($scenarios, static fn (Scenario $left, Scenario $right): int => strcmp($left->name, $right->name));
return $scenarios;
}
/**
* @return list<Scenario>
*/
public function category(string $category): array
{
return array_values(array_filter(
$this->all(),
static fn (Scenario $scenario): bool => $scenario->category() === $category,
));
}
/**
* @return array<string, mixed>
*/
private function loadDefinition(string $path): array
{
$definition = Json::decodeFile($path);
if (array_is_list($definition)) {
throw new \RuntimeException(sprintf('Scenario definition must decode to an object: %s', $path));
}
$normalized = [];
foreach ($definition as $key => $value) {
if (!is_string($key)) {
throw new \RuntimeException(sprintf('Scenario definition contains a non-string key: %s', $path));
}
$normalized[$key] = $value;
}
return $normalized;
}
}