Passed
Branch master (dfd9e6)
by Joao
01:44
created

OpenApiSchema::getResponseBody()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 4
1
<?php
2
3
namespace ByJG\ApiTools\OpenApi;
4
5
use ByJG\ApiTools\Base\Body;
6
use ByJG\ApiTools\Base\Schema;
7
use ByJG\ApiTools\Exception\DefinitionNotFoundException;
8
use ByJG\ApiTools\Exception\InvalidDefinitionException;
9
use ByJG\ApiTools\Exception\InvalidRequestException;
10
use ByJG\ApiTools\Exception\NotMatchedException;
11
use ByJG\Util\Uri;
12
13
class OpenApiSchema extends Schema
14
{
15
16
    protected array $serverVariables = [];
17
18
    /**
19
     * Initialize with schema data, which can be a PHP array or encoded as JSON.
20
     *
21
     * @param array|string $data
22
     */
23
    public function __construct(array|string $data)
24
    {
25
        // when given a string, decode from JSON
26
        if (is_string($data)) {
0 ignored issues
show
introduced by
The condition is_string($data) is always false.
Loading history...
27
            $data = json_decode($data, true);
28
        }
29
        $this->jsonFile = $data;
30
    }
31
32
    public function getServerUrl(): string
33
    {
34
        if (!isset($this->jsonFile['servers'])) {
35
            return '';
36
        }
37
        $serverUrl = $this->jsonFile['servers'][0]['url'];
38
39
        if (isset($this->jsonFile['servers'][0]['variables'])) {
40
            foreach ($this->jsonFile['servers'][0]['variables'] as $var => $value) {
41
                if (!isset($this->serverVariables[$var])) {
42
                    $this->serverVariables[$var] = $value['default'];
43
                }
44
            }
45
        }
46
47
        foreach ($this->serverVariables as $var => $value) {
48
            $serverUrl = (string)preg_replace("/\{$var}/", $value, $serverUrl);
49
        }
50
51
        return $serverUrl;
52
    }
53
54
    public function getBasePath(): string
55
    {
56
        $uriServer = new Uri($this->getServerUrl());
57
        return $uriServer->getPath();
58
    }
59
60
    /**
61
     * @inheritDoc
62
     */
63
    protected function validateArguments(string $parameterIn, array $parameters, array $arguments): void
64
    {
65
        foreach ($parameters as $parameter) {
66
            if (isset($parameter['$ref'])) {
67
                $paramParts = explode("/", $parameter['$ref']);
68
                if (count($paramParts) != 4 || $paramParts[0] != "#" || $paramParts[1] != self::SWAGGER_COMPONENTS || $paramParts[2] != self::SWAGGER_PARAMETERS) {
69
                    throw new InvalidDefinitionException(
70
                        "Not get the reference in the expected format #/components/parameters/<NAME>"
71
                    );
72
                }
73
                if (!isset($this->jsonFile[self::SWAGGER_COMPONENTS][self::SWAGGER_PARAMETERS][$paramParts[3]])) {
74
                    throw new DefinitionNotFoundException(
75
                        "Not find reference #/components/parameters/$paramParts[3]"
76
                    );
77
                }
78
                $parameter = $this->jsonFile[self::SWAGGER_COMPONENTS][self::SWAGGER_PARAMETERS][$paramParts[3]];
79
            }
80
            if ($parameter['in'] === $parameterIn &&
81
                $parameter['schema']['type'] === "integer"
82
                && filter_var($arguments[$parameter['name']], FILTER_VALIDATE_INT) === false) {
83
                throw new NotMatchedException('Path expected an integer value');
84
            }
85
        }
86
    }
87
88
    /**
89
     * @param $name
90
     * @return mixed
91
     * @throws DefinitionNotFoundException
92
     * @throws InvalidDefinitionException
93
     */
94
    public function getDefinition($name): mixed
95
    {
96
        $nameParts = explode('/', $name);
97
98
        if (count($nameParts) < 4 || $nameParts[0] !== '#') {
99
            throw new InvalidDefinitionException('Invalid Component');
100
        }
101
102
        if (!isset($this->jsonFile[$nameParts[1]][$nameParts[2]][$nameParts[3]])) {
103
            throw new DefinitionNotFoundException("Component'$name' not found");
104
        }
105
106
        return $this->jsonFile[$nameParts[1]][$nameParts[2]][$nameParts[3]];
107
    }
108
109
    /**
110
     * @inheritDoc
111
     * @throws InvalidRequestException
112
     */
113
    public function getRequestParameters(string $path, string $method): Body
114
    {
115
        $structure = $this->getPathDefinition($path, $method);
116
117
        if (!isset($structure['requestBody'])) {
118
            return new OpenApiRequestBody($this, "$method $path", []);
119
        }
120
        return new OpenApiRequestBody($this, "$method $path", $structure['requestBody']);
121
    }
122
123
    public function setServerVariable(string $var, string $value): void
124
    {
125
        $this->serverVariables[$var] = $value;
126
    }
127
128
    /**
129
     * @inheritDoc
130
     */
131
    public function getResponseBody(Schema $schema, string $name, array $structure, bool $allowNullValues = false): Body
132
    {
133
        return new OpenApiResponseBody($schema, $name, $structure, $allowNullValues);
134
    }
135
}
136