OpenAPIExpander   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 13
eloc 29
dl 0
loc 75
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getParameter() 0 7 2
A getComponent() 0 7 2
A expand() 0 13 3
A diveAndReplace() 0 22 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PavelJanda\OpenAPIExpander;
6
7
final class OpenAPIExpander
8
{
9
10
	/**
11
	 * @var array
12
	 */
13
	private $components = [];
14
15
	/**
16
	 * @var array
17
	 */
18
	private $parameters = [];
19
20
21
	public function expand(array $specData): array
22
	{
23
		foreach ($specData['components']['schemas'] as $componentName => $component) {
24
			$this->components['#/components/schemas/' . $componentName] = $component;
25
		}
26
27
		foreach ($specData['components']['parameters'] as $parametersName => $parameters) {
28
			$this->parameters['#/components/parameters/' . $parametersName] = $parameters;
29
		}
30
31
		$this->diveAndReplace($specData);
32
33
		return $specData;
34
	}
35
36
37
	private function diveAndReplace(array &$refNode): void
38
	{
39
		foreach ($refNode as $key => $node) {
40
			if (is_array($refNode[$key])) {
41
				$this->diveAndReplace($refNode[$key]);
42
			} elseif ($key === '$ref' && is_string($node)) {
43
				if (strpos($node, '#/components/schemas/') !== false) {
44
					$name = str_replace('#/components/schemas/', '', $node);
45
46
					$refNode[$name] = $this->getComponent($node);
47
48
					unset($refNode['$ref']);
49
50
					$this->diveAndReplace($refNode[$name]);
51
				} else {
52
					$name = str_replace('#/components/parameters/', '', $node);
53
54
					$refNode[$name] = $this->getParameter($node);
55
56
					unset($refNode['$ref']);
57
58
					$this->diveAndReplace($refNode[$name]);
59
				}
60
			}
61
		}
62
	}
63
64
65
	private function getComponent(string $name): array
66
	{
67
		if (!isset($this->components[$name])) {
68
			throw new \RuntimeException(sprintf('Component %s not found', $name));
69
		}
70
71
		return $this->components[$name];
72
	}
73
74
75
	private function getParameter(string $name): array
76
	{
77
		if (!isset($this->parameters[$name])) {
78
			throw new \RuntimeException(sprintf('Parameter %s not found', $name));
79
		}
80
81
		return $this->parameters[$name];
82
	}
83
}
84