1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Shlinkio\Shlink\Rest; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
|
9
|
|
|
use function Functional\first; |
10
|
|
|
use function Functional\map; |
11
|
|
|
use function Shlinkio\Shlink\Common\loadConfigFromGlob; |
12
|
|
|
use function sprintf; |
13
|
|
|
|
14
|
|
|
class ConfigProvider |
15
|
|
|
{ |
16
|
|
|
private const ROUTES_PREFIX = '/rest/v{version:1|2}'; |
17
|
|
|
private const UNVERSIONED_ROUTES_PREFIX = '/rest'; |
18
|
|
|
public const UNVERSIONED_HEALTH_ENDPOINT_NAME = 'unversioned_health'; |
19
|
|
|
|
20
|
|
|
private Closure $loadConfig; |
21
|
|
|
|
22
|
3 |
|
public function __construct(?callable $loadConfig = null) |
23
|
|
|
{ |
24
|
3 |
|
$this->loadConfig = Closure::fromCallable($loadConfig ?? fn (string $glob) => loadConfigFromGlob($glob)); |
25
|
|
|
} |
26
|
|
|
|
27
|
3 |
|
public function __invoke(): array |
28
|
|
|
{ |
29
|
3 |
|
$config = ($this->loadConfig)(__DIR__ . '/../config/{,*.}config.php'); |
30
|
3 |
|
return $this->applyRoutesPrefix($config); |
31
|
|
|
} |
32
|
|
|
|
33
|
3 |
|
private function applyRoutesPrefix(array $config): array |
34
|
|
|
{ |
35
|
3 |
|
$routes = $config['routes'] ?? []; |
36
|
3 |
|
$healthRoute = $this->buildUnversionedHealthRouteFromExistingRoutes($routes); |
37
|
|
|
|
38
|
|
|
$prefixRoute = static function (array $route) { |
39
|
3 |
|
['path' => $path] = $route; |
40
|
3 |
|
$route['path'] = sprintf('%s%s', self::ROUTES_PREFIX, $path); |
41
|
|
|
|
42
|
3 |
|
return $route; |
43
|
3 |
|
}; |
44
|
3 |
|
$prefixedRoutes = map($routes, $prefixRoute); |
45
|
|
|
|
46
|
3 |
|
$config['routes'] = $healthRoute !== null ? [...$prefixedRoutes, $healthRoute] : $prefixedRoutes; |
47
|
|
|
|
48
|
3 |
|
return $config; |
49
|
|
|
} |
50
|
|
|
|
51
|
3 |
|
private function buildUnversionedHealthRouteFromExistingRoutes(array $routes): ?array |
52
|
|
|
{ |
53
|
3 |
|
$healthRoute = first($routes, fn (array $route) => $route['path'] === '/health'); |
54
|
3 |
|
if ($healthRoute === null) { |
55
|
1 |
|
return null; |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
$path = $healthRoute['path']; |
59
|
2 |
|
$healthRoute['path'] = sprintf('%s%s', self::UNVERSIONED_ROUTES_PREFIX, $path); |
60
|
2 |
|
$healthRoute['name'] = self::UNVERSIONED_HEALTH_ENDPOINT_NAME; |
61
|
|
|
|
62
|
2 |
|
return $healthRoute; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|