76 lines
2.0 KiB
PHP
76 lines
2.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Service;
|
|
|
|
use App\Model\DomainConfig;
|
|
use Symfony\Component\HttpFoundation\RequestStack;
|
|
|
|
/**
|
|
* Resolves domain-specific configuration based on the current request host.
|
|
*
|
|
* Matches the request host against configured domain patterns, supporting both
|
|
* exact matches and subdomain matching (e.g., "example.com" matches "www.example.com").
|
|
* Returns a default configuration when no matching domain is found.
|
|
*/
|
|
class DomainConfigProvider
|
|
{
|
|
/**
|
|
* @var array<string, DomainConfig>
|
|
*/
|
|
private array $configCache = [];
|
|
|
|
/**
|
|
* @param array<string, array{theme?: string, gtm_id?: string, cmp_url?: string}> $domainConfig
|
|
*/
|
|
public function __construct(
|
|
private readonly array $domainConfig,
|
|
private readonly RequestStack $requestStack,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* Returns the configuration for the current request host.
|
|
*/
|
|
public function getConfig(): DomainConfig
|
|
{
|
|
$request = $this->requestStack->getCurrentRequest();
|
|
|
|
if (null === $request) {
|
|
return DomainConfig::default();
|
|
}
|
|
|
|
return $this->getConfigForHost($request->getHost());
|
|
}
|
|
|
|
/**
|
|
* Returns the configuration for a specific host.
|
|
*
|
|
* @param string $host The host to resolve configuration for
|
|
*/
|
|
public function getConfigForHost(string $host): DomainConfig
|
|
{
|
|
$host = strtolower($host);
|
|
|
|
if (isset($this->configCache[$host])) {
|
|
return $this->configCache[$host];
|
|
}
|
|
|
|
foreach ($this->domainConfig as $pattern => $config) {
|
|
$pattern = strtolower($pattern);
|
|
|
|
if ($host === $pattern || str_ends_with($host, '.'.$pattern)) {
|
|
$domainConfig = DomainConfig::fromArray($config);
|
|
$this->configCache[$host] = $domainConfig;
|
|
|
|
return $domainConfig;
|
|
}
|
|
}
|
|
|
|
$this->configCache[$host] = DomainConfig::default();
|
|
|
|
return $this->configCache[$host];
|
|
}
|
|
}
|