<?php declare(strict_types=1);
namespace Shopware\B2B\Shop\BridgePlatform;
use Shopware\B2B\Common\IdValue;
use Shopware\B2B\SalesRepresentative\Framework\SalesRepresentativeIdentity;
use Shopware\B2B\StoreFrontAuthentication\BridgePlatform\B2bIdentityIdStruct;
use Shopware\B2B\StoreFrontAuthentication\BridgePlatform\SalesChannelContextAuthStorageAdapter;
use Shopware\Core\System\SalesChannel\Context\SalesChannelContextFactory;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Component\DependencyInjection\ContainerInterface;
use function is_string;
use function unserialize;
class SalesChannelContextFactoryDecorator extends SalesChannelContextFactory
{
private SalesChannelContextFactory $decorated;
private ContainerInterface $container;
public function __construct(SalesChannelContextFactory $decorated, ContainerInterface $container)
{
$this->decorated = $decorated;
$this->container = $container;
}
public function create(string $token, string $salesChannelId, array $options = []): SalesChannelContext
{
$context = $this->decorated->create($token, $salesChannelId, $options);
if (isset($options[SalesChannelContextAuthStorageAdapter::IDENTITY_ID_KEY])) {
$this->addB2bExtension(
$context,
$this->createIdValue($options[SalesChannelContextAuthStorageAdapter::IDENTITY_ID_KEY]),
SalesChannelContextAuthStorageAdapter::IDENTITY_ID_KEY
);
}
if (isset($options[SalesRepresentativeIdentity::AUTH_ID_KEY])) {
$this->addB2bExtension(
$context,
$this->createIdValue($options[SalesRepresentativeIdentity::AUTH_ID_KEY]),
SalesRepresentativeIdentity::AUTH_ID_KEY
);
}
if (!$this->isSalesChannelContextProviderInitialized()) {
return $context;
}
$salesChannelContextProvider = $this->getSalesChannelContextProvider();
if (!$salesChannelContextProvider->hasSalesChannelContext()) {
$salesChannelContextProvider->setSalesChannelContext($context);
}
return $context;
}
/**
* @internal
*/
protected function getSalesChannelContextProvider(): ContextProvider
{
return $this->container->get('b2b_shop.context_provider');
}
/**
* @internal
*/
protected function isSalesChannelContextProviderInitialized(): bool
{
return $this->container->initialized('b2b_shop.context_provider');
}
/**
* @internal
*/
protected function addB2bExtension(SalesChannelContext $context, $identityId, string $name): void
{
$context->addExtension(
$name,
new B2bIdentityIdStruct(IdValue::create($identityId))
);
}
/**
* @internal
*/
protected function createIdValue($value): IdValue
{
if (is_string($value)) {
$identity = unserialize($value);
if ($identity instanceof B2bIdentityIdStruct) {
return $identity->getIdentityId();
}
if ($identity instanceof IdValue) {
return $identity;
}
}
return IdValue::create($value);
}
}