shlink/module/Rest/src/ConfigProvider.php

65 lines
1.9 KiB
PHP
Raw Normal View History

2016-07-19 18:07:59 +03:00
<?php
2019-10-05 18:26:10 +03:00
2017-10-12 11:13:20 +03:00
declare(strict_types=1);
2016-07-19 18:07:59 +03:00
namespace Shlinkio\Shlink\Rest;
use Closure;
use function Functional\first;
use function Functional\map;
use function Shlinkio\Shlink\Config\loadConfigFromGlob;
2018-12-23 12:18:38 +03:00
use function sprintf;
2016-07-19 18:07:59 +03:00
class ConfigProvider
{
private const ROUTES_PREFIX = '/rest/v{version:1|2}';
private const UNVERSIONED_ROUTES_PREFIX = '/rest';
public const UNVERSIONED_HEALTH_ENDPOINT_NAME = 'unversioned_health';
2018-01-07 22:45:05 +03:00
private Closure $loadConfig;
public function __construct(?callable $loadConfig = null)
{
$this->loadConfig = Closure::fromCallable($loadConfig ?? fn (string $glob) => loadConfigFromGlob($glob));
}
2020-01-01 22:48:31 +03:00
public function __invoke(): array
2016-07-19 18:07:59 +03:00
{
$config = ($this->loadConfig)(__DIR__ . '/../config/{,*.}config.php');
2018-01-07 22:46:28 +03:00
return $this->applyRoutesPrefix($config);
2018-01-07 22:45:05 +03:00
}
private function applyRoutesPrefix(array $config): array
{
$routes = $config['routes'] ?? [];
$healthRoute = $this->buildUnversionedHealthRouteFromExistingRoutes($routes);
2018-01-07 22:45:05 +03:00
$prefixRoute = static function (array $route) {
2018-12-29 13:24:55 +03:00
['path' => $path] = $route;
$route['path'] = sprintf('%s%s', self::ROUTES_PREFIX, $path);
return $route;
};
$prefixedRoutes = map($routes, $prefixRoute);
$config['routes'] = $healthRoute !== null ? [...$prefixedRoutes, $healthRoute] : $prefixedRoutes;
2018-01-07 22:45:05 +03:00
return $config;
2016-07-19 18:07:59 +03:00
}
private function buildUnversionedHealthRouteFromExistingRoutes(array $routes): ?array
{
$healthRoute = first($routes, fn (array $route) => $route['path'] === '/health');
if ($healthRoute === null) {
return null;
}
$path = $healthRoute['path'];
$healthRoute['path'] = sprintf('%s%s', self::UNVERSIONED_ROUTES_PREFIX, $path);
$healthRoute['name'] = self::UNVERSIONED_HEALTH_ENDPOINT_NAME;
return $healthRoute;
}
2016-07-19 18:07:59 +03:00
}