<?php
namespace B2bSellersCore\Components\B2bPlatform\Subscriber;
use B2bSellersCore\Components\B2bPlatform\Exception\B2bPlatformContextException;
use B2bSellersCore\Components\Employee\Exception\InsufficientEmployeePermissionException;
use B2bSellersCore\Components\Framework\Routing\Annotation\B2bPlatformContextRequired;
use B2bSellersCore\Components\Framework\Routing\Annotation\B2bPlatformPermission;
use Shopware\Core\Framework\Routing\Event\SalesChannelContextResolvedEvent;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
class RequestSubscriber implements EventSubscriberInterface
{
private RequestStack $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public static function getSubscribedEvents(): array
{
return [
SalesChannelContextResolvedEvent::class => 'checkB2bPlatformAnnotations'
];
}
public function checkB2bPlatformAnnotations(SalesChannelContextResolvedEvent $event)
{
$this->validateB2bPlatformContextRequired($this->getRequest(), $event->getSalesChannelContext());
$this->validateB2bPlatformPermission($this->getRequest(), $event->getSalesChannelContext());
}
private function validateB2bPlatformContextRequired(Request $request, SalesChannelContext $context): void
{
/** @var B2bPlatformContextRequired|null $b2bPlatformContextRequired */
$b2bPlatformContextRequired = $request->attributes->get(B2bPlatformContextRequired::ATTRIBUTE_B2B_PlATFORM_CONTEXT_REQUIRED);
if ($b2bPlatformContextRequired === null) {
return;
}
if ($b2bPlatformContextRequired->hasB2bPlatformContext($context)) {
return;
}
throw new B2bPlatformContextException();
}
private function validateB2bPlatformPermission(Request $request, SalesChannelContext $context): void
{
/** @var B2bPlatformPermission|null $b2bPlatformPermission */
$b2bPlatformPermission = $request->attributes->get(B2bPlatformPermission::ATTRIBUTE_B2B_PlATFORM_PERMISSION);
if ($b2bPlatformPermission === null) {
return;
}
if ($b2bPlatformPermission->hasB2bPlatformPermission($context)) {
return;
}
throw new InsufficientEmployeePermissionException();
}
private function getRequest(): Request
{
return $this->requestStack->getCurrentRequest();
}
}