<?php
declare(strict_types=1);
namespace Orcamultimedia\OciPunchout\Subscriber;
use Shopware\Core\Framework\Event\BeforeSendResponseEvent;
use Shopware\Core\PlatformRequest;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
class ResponseHeaderSubscriber implements EventSubscriberInterface
{
/**
* @var array
*/
private array $frameancestors;
public function __construct(
array $frameancestors
)
{
$this->frameancestors = $frameancestors;
}
public static function getSubscribedEvents(): array
{
return [
BeforeSendResponseEvent::class => [['beforeSendOciResponse']]
];
}
public function beforeSendOciResponse(BeforeSendResponseEvent $event): void
{
$response = $event->getResponse();
$request = $event->getRequest();
$requestCookie = $request->cookies->get('sapoci');
$responseCookies = $response->headers->getCookies();
$responseCookie = array_filter($responseCookies, fn(Cookie $cookie) => $cookie->getName() === 'sapoci');
$isPunchout = false;
if (
$response->getStatusCode() !== Response::HTTP_OK
&& $response->getStatusCode() !== Response::HTTP_NOT_FOUND
&& $response->getStatusCode() !== Response::HTTP_FOUND
) {
return;
}
if ($request->hasSession()) {
$session = $request->getSession();
} elseif ($requestCookie == 'is-punchout') {
$isPunchout = true;
} elseif ($responseCookie && $responseCookie[0]->getValue() == 'is-punchout') {
$isPunchout = true;
} else {
return;
}
if (!$isPunchout && (isset($session) && !$session->get('oci'))) {
return;
}
if ($response->headers->has(PlatformRequest::HEADER_FRAME_OPTIONS)) {
$response->headers->remove(PlatformRequest::HEADER_FRAME_OPTIONS);
}
$response->headers->set(
'Content-Security-Policy',
sprintf("frame-ancestors %s", implode(' ', $this->frameancestors)),
false
);
foreach ($response->headers->getCookies() as $cookie) {
$response->headers->setCookie($cookie->withSameSite(Cookie::SAMESITE_NONE)->withSecure());
}
$event->setResponse($response);
}
}