Completed
Pull Request — develop (#603)
by Alejandro
04:37
created

ConfigProvider   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 23
c 0
b 0
f 0
dl 0
loc 49
rs 10
ccs 23
cts 23
cp 1
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A buildUnversionedHealthRouteFromExistingRoutes() 0 12 2
A __invoke() 0 4 1
A applyRoutesPrefix() 0 16 2
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