Skip to content

Commit cbd63d5

Browse files
committed
support server url
1 parent 22ec7ff commit cbd63d5

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/Tqdev/PhpCrudApi/OpenApi/OpenApiBuilder.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,22 @@ public function __construct(ReflectionService $reflection, $base)
4040
$this->openapi = new OpenApiDefinition($base);
4141
}
4242

43+
private function getServerUrl(): String
44+
{
45+
$protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] ?: @$_SERVER['REQUEST_SCHEME'] ?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
46+
$port = @intval($_SERVER['HTTP_X_FORWARDED_PORT']) ?: @intval($_SERVER["SERVER_PORT"]) ?: (($protocol === 'https') ? 443 : 80);
47+
$host = @explode(":", $_SERVER['HTTP_HOST'])[0] ?: @$_SERVER['SERVER_NAME'] ?: @$_SERVER['SERVER_ADDR'];
48+
$port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
49+
$path = @trim(substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '/openapi')), '/');
50+
return sprintf('%s://%s%s/%s', $protocol, $host, $port, $path);
51+
}
52+
4353
public function build(): OpenApiDefinition
4454
{
4555
$this->openapi->set("openapi", "3.0.0");
56+
if (!$this->openapi->has("servers") && isset($_SERVER['REQUEST_URI'])) {
57+
$this->openapi->set("servers|0|url", $this->getServerUrl());
58+
}
4659
$tableNames = $this->reflection->getTableNames();
4760
foreach ($tableNames as $tableName) {
4861
$this->setPath($tableName);

src/Tqdev/PhpCrudApi/OpenApi/OpenApiDefinition.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,20 @@ public function set(String $path, $value) /*: void*/
2424
$current = $value;
2525
}
2626

27+
public function has(String $path): bool
28+
{
29+
$parts = explode('|', trim($path, '|'));
30+
$current = &$this->root;
31+
while (count($parts) > 0) {
32+
$part = array_shift($parts);
33+
if (!isset($current[$part])) {
34+
return false;
35+
}
36+
$current = &$current[$part];
37+
}
38+
return true;
39+
}
40+
2741
public function jsonSerialize()
2842
{
2943
return $this->root;

0 commit comments

Comments
 (0)