-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathDefinitionsCollector.php
More file actions
57 lines (46 loc) · 1.83 KB
/
Copy pathDefinitionsCollector.php
File metadata and controls
57 lines (46 loc) · 1.83 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
<?php
declare(strict_types=1);
namespace Helmich\Schema2Class\Generator\Definitions;
use Helmich\Schema2Class\Generator\GeneratorRequest;
class DefinitionsCollector
{
public function __construct(protected readonly GeneratorRequest $generatorRequest)
{
}
/**
* @return \Generator<string, Definition>
*/
public function collect(array $schema, string $path = ''): \Generator {
if (isset($schema['definitions'])) {
yield from $this->findNestedDefinitions($schema['definitions'], ($path ?: '#') . '/definitions');
}
if (isset($schema['$defs'])) {
yield from $this->findNestedDefinitions($schema['$defs'], ($path ?: '#') . '/$defs');
}
}
private function findNestedDefinitions(array $definitions, string $path): \Generator {
foreach ($definitions as $key => $value) {
$newPath = $path . '/' . $key;
yield $newPath => $this->pathToClassName($newPath, $value);
if (is_array($value)) {
yield from $this->collect($value, $newPath);
}
}
}
private function pathToClassName(string $path, array $schema): Definition {
$parts = array_map(
fn ($part) => str_replace(' ', '', ucwords(str_replace('_', ' ', $part))),
explode('/', ltrim(str_replace('$defs', 'Defs', $path), '#/'))
);
$className = array_pop($parts);
$namespace = $this->generatorRequest->getTargetNamespace() . '\\' . implode('\\', $parts);
$directory = $this->generatorRequest->getTargetDirectory() . '/' . implode('/', $parts);
return new Definition(
namespace: $namespace,
directory: $directory,
classFQN: $namespace . '\\' . $className,
className: $className,
schema: $schema,
);
}
}