87 lines
2.0 KiB
PHP
87 lines
2.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace KupShop\KupShopBundle\Context;
|
|
|
|
use KupShop\KupShopBundle\Entity\Site;
|
|
use KupShop\KupShopBundle\Util\Contexts;
|
|
use KupShop\KupShopBundle\Util\Entity\EntityUtil;
|
|
use KupShop\KupShopBundle\Util\Functional\Mapping;
|
|
|
|
class SiteContext implements ContextInterface
|
|
{
|
|
protected ?int $activeId = null;
|
|
|
|
protected ?array $supported = null;
|
|
|
|
public function __construct(private EntityUtil $entityUtil)
|
|
{
|
|
}
|
|
|
|
public function activate(string|int $id): bool
|
|
{
|
|
$this->activeId = (int) $id;
|
|
|
|
return true;
|
|
}
|
|
|
|
public function getActiveId(): int
|
|
{
|
|
if (is_null($this->activeId)) {
|
|
$this->activeId = $this->loadActive();
|
|
}
|
|
|
|
return $this->activeId;
|
|
}
|
|
|
|
public function getActive(): Site
|
|
{
|
|
return $this->getSupported()[$this->getActiveId()];
|
|
}
|
|
|
|
public function clearCache(): void
|
|
{
|
|
$this->activeId = null;
|
|
}
|
|
|
|
public function isValid(string $id): bool
|
|
{
|
|
return array_key_exists($id, $this->getSupported());
|
|
}
|
|
|
|
/**
|
|
* @return Site[]
|
|
*/
|
|
public function getSupported(): array
|
|
{
|
|
if ($this->supported === null) {
|
|
$this->supported = Mapping::mapKeys(sqlQueryBuilder()
|
|
->select('*')
|
|
->from('sites')
|
|
->execute()
|
|
->fetchAllAssociative(),
|
|
fn ($k, $v) => [$v['id'], $this->entityUtil->createEntity($v, Site::class)]
|
|
);
|
|
}
|
|
|
|
return $this->supported;
|
|
}
|
|
|
|
protected function loadActive(): int
|
|
{
|
|
$domain = Contexts::get(DomainContext::class)->getActiveId();
|
|
$language = Contexts::get(LanguageContext::class)->getActiveId();
|
|
|
|
$supported = $this->getSupported();
|
|
|
|
foreach ($supported as $site) {
|
|
if ($site->getDomain() === $domain && $site->getLanguage() === $language) {
|
|
return $site->getId();
|
|
}
|
|
}
|
|
|
|
return reset($supported)->getId();
|
|
}
|
|
}
|