<?php
namespace GlobusSW6\Subscriber;
use GlobusSW6\Service\PageMetaData\PageMetaRobotTagService;
use Psr\Log\LoggerInterface;
use Shopware\Storefront\Event\StorefrontRenderEvent;
use Shopware\Storefront\Page\Checkout\Offcanvas\OffcanvasCartPage;
use Shopware\Storefront\Page\Page;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class RobotsMetaDataSubscriber implements EventSubscriberInterface
{
private PageMetaRobotTagService $robotTagService;
private LoggerInterface $logger;
public function __construct(PageMetaRobotTagService $robotTagService, LoggerInterface $logger)
{
$this->robotTagService = $robotTagService;
$this->logger = $logger;
}
public static function getSubscribedEvents()
{
return [
StorefrontRenderEvent::class => 'onStorefrontRender'
];
}
/**
* @param StorefrontRenderEvent $event
*/
public function onStorefrontRender(StorefrontRenderEvent $event): void
{
// StorefrontRenderEvent is dispatched by offcanvas cart as well. There it has no Page class instance, hence the check.
if (!isset($event->getParameters()['page'])
|| !($event->getParameters()['page'] instanceof Page
|| $event->getParameters()['page'] instanceof OffcanvasCartPage)) {
return;
}
$page = $event->getParameters()['page'];
if (empty($page)) {
return;
}
// Check if metaInformationMethod exists
if (!is_object($page) || !method_exists($page,'getMetaInformation')) {
return;
}
// Check if metaInformation is set
if (empty($page->getMetaInformation())) {
return;
}
// Get metaInformation
/** @var MetaInformation $metaInformation */
$metaInformation = $page->getMetaInformation();
//Check if SalesChannelId is set
if (!$event->getSalesChannelContext()->getSalesChannelId()) {
return;
}
$salesChannelId = $event->getSalesChannelContext()->getSalesChannelId();
try {
$this->robotTagService->setRobotTags($page, $salesChannelId);
} catch (\Throwable $t) {
$this->logger->error(__CLASS__ . ":" . __FUNCTION__ . ":" . __LINE__ . ":\n" . $t->getMessage());
}
}
}