Files
kupshop/bundles/KupShop/KupShopBundle/Context/DomainContext.php
2025-08-02 16:30:27 +02:00

126 lines
2.5 KiB
PHP

<?php
namespace KupShop\KupShopBundle\Context;
use KupShop\KupShopBundle\Config;
use Symfony\Component\HttpFoundation\RequestStack;
class DomainContext implements ContextInterface
{
/** @var string */
protected $activeId;
/** @var string[] */
protected $domains;
/** @var RequestStack */
protected $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function activate(string $id)
{
$this->activeId = $id;
return true;
}
/**
* @return string[]
*/
public function getSupported()
{
return $this->domains;
}
/**
* @return string[]
*/
public function getSupportedWithScheme()
{
$domains = [];
foreach ($this->domains as $domain) {
$domains[$domain] = 'https://'.$domain;
}
return $domains;
}
/**
* @return bool
*/
protected function validate($id)
{
return array_search($id, $this->getSupported()) !== false;
}
protected function loadActive()
{
if ($request = $this->requestStack->getMainRequest()) {
$domain = $request->getHost();
if ($this->validate($domain)) {
return $domain;
}
}
// Return CI domain if set
if (isAutoDeploy()) {
return explode(',', getenv('VIRTUAL_HOST'))[0];
}
// Return local domain if is development
if (isDevelopment()) {
return 'www.kupshop.local';
}
return $this->getSupported()[0];
}
public function getActive()
{
return $this->getActiveId();
}
public function getActiveWithScheme()
{
return 'https://'.$this->getActiveId();
}
public function getActiveId(): string
{
if (is_null($this->activeId)) {
$this->activeId = $this->loadActive();
}
return $this->activeId;
}
/**
* @param string[] $domains
*/
public function setDomains(array $domains): DomainContext
{
if ($domains) {
$this->domains = $domains;
} else {
$domain = Config::get()->getFromArray('Addr')['print'];
$this->domains = [rtrim($domain, '/')];
}
return $this;
}
public function clearCache(): void
{
$this->activeId = null;
}
public function isValid(string $id): bool
{
return $this->validate($id);
}
}