Lines 100.00% 12 / 12
Functions and Methods 100.00% 3 / 3
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
AdminRoute 100.00% 12 / 12 100.00% 3 / 3 7 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 fromPath 100.00% 10 / 10 100.00% 1 / 1 5
 allowsMethod 100.00% 1 / 1 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Http\Admin;
6
7final readonly class AdminRoute
8{
9    private const string METRICS_PATH = '/metrics';
10
11    private const string APPS_PATH = '~\A/api/apps(?:/([^/]+)(?:/(pause|resume|reset))?)?\z~';
12
13    private const string WORKER_RESTART_PATH = '~\A/api/workers/([^/]+)/restart\z~';
14
15    public function __construct(
16        public AdminAction $action,
17        public ?string $resourceId,
18    ) {}
19
20    public static function fromPath(string $path): ?self
21    {
22        if ($path === self::METRICS_PATH) {
23            return new self(AdminAction::ShowMetrics, null);
24        }
25
26        if (preg_match(self::WORKER_RESTART_PATH, $path, $matches) === 1) {
27            return new self(AdminAction::RestartWorker, rawurldecode($matches[1]));
28        }
29
30        if (preg_match(self::APPS_PATH, $path, $matches) !== 1) {
31            return null;
32        }
33
34        $appId = $matches[1] ?? '';
35
36        if ($appId === '') {
37            return new self(AdminAction::ListApps, null);
38        }
39
40        return new self(AdminAction::tryFrom($matches[2] ?? '') ?? AdminAction::ShowApp, rawurldecode($appId));
41    }
42
43    public function allowsMethod(string $method): bool
44    {
45        return \in_array($method, $this->action->listAllowedMethods(), true);
46    }
47}