Lines 96.15% 25 / 26
Methods 66.66% 2 / 3
Classes 0.00% 0 / 1
Covered by tests of size
Name Lines Methods CRAP
 resolve 100.00% 16 / 16 100.00% 1 / 1 3
 readIntEnv 83.33% 5 / 6 0.00% 0 / 1 4.07
 readStringEnv 100.00% 4 / 4 100.00% 1 / 1 3
25class TenantContextResolver
26{
27    public function resolve(?Request $request = null): TenantContext
28    {
29        $request ??= Request::createFromGlobals();
30        $hostname = $request->getHost();
31
32        if ($hostname === '') {
33            $hostname = 'localhost';
34        }
35
36        $configDir = defined('PMF_CONFIG_DIR') ? (string) PMF_CONFIG_DIR : '';
37        $tablePrefix = Database::getTablePrefix();
38
39        $tenantId = $this->readIntEnv('PMF_TENANT_ID') ?? 0;
40        $plan = $this->readStringEnv('PMF_TENANT_PLAN') ?? 'free';
41
42        $quotas = new TenantQuotas(
43            $this->readIntEnv('PMF_TENANT_QUOTA_MAX_FAQS'),
44            $this->readIntEnv('PMF_TENANT_QUOTA_MAX_ATTACHMENT_SIZE'),
45            $this->readIntEnv('PMF_TENANT_QUOTA_MAX_USERS'),
46            $this->readIntEnv('PMF_TENANT_QUOTA_MAX_API_REQUESTS'),
47            $this->readIntEnv('PMF_TENANT_QUOTA_MAX_CATEGORIES'),
48        );
49
50        return new TenantContext($tenantId, $hostname, $tablePrefix, $configDir, $plan, $quotas);
51    }
52
53    private function readIntEnv(string $key): ?int
54    {
55        $value = getenv($key);
56        if ($value === false || $value === '') {
57            return null;
58        }
59
60        if (!is_numeric($value)) {
61            return null;
62        }
63
64        return (int) $value;
65    }
66
67    private function readStringEnv(string $key): ?string
68    {
69        $value = getenv($key);
70        if ($value === false || $value === '') {
71            return null;
72        }
73
74        return trim($value);
75    }
76}