<?php declare(strict_types=1);
namespace Ecd\econdWebAnalytics\Storefront\Page\Product\Subscriber;
use Shopware\Core\Framework\Struct\ArrayEntity;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductPageLoadedEventSubscriber implements EventSubscriberInterface {
private $systemConfigService, $breadcrumbHelper;
public function __construct(SystemConfigService $systemConfigService)
{
$this->systemConfigService = $systemConfigService;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents()
{
return [
ProductPageLoadedEvent::class => 'onProductPageLoadedEvent'
];
}
public function onProductPageLoadedEvent(ProductPageLoadedEvent $event) : void
{
$group = '';
$config = $this->systemConfigService->getDomain('econdWebAnalytics');
$page = $event->getPage();
$product = $page->getProduct();
$categoryTree = $product->getCategoryTree();
$navigationTree = $page->getHeader()->getNavigation()->getTree();
if($categoryTree != null) {
foreach (array_reverse($categoryTree) as $catId) {
$catTreeItem = $this->findTreeItemByCategoryId($catId, $navigationTree);
if ($catTreeItem) break;
}
$breadcrumb = $catTreeItem->getCategory()->getPlainBreadcrumb();
// remove first element of array
array_shift($breadcrumb);
// key last key of array
$lastkey = array_key_last($breadcrumb);
foreach($breadcrumb as $k => $item) {
$group .= $item;
if($k != $lastkey) {
$group .= '/';
}
}
}else {
$group = null;
}
$variant = [
'econdWebAnalytics.config.var1' => '',
'econdWebAnalytics.config.var2' => '',
'econdWebAnalytics.config.var3' => ''
];
foreach($page->getSelectedOptions() as $option){
foreach ($config as $k => &$item) {
if($item == $option->getGroupId()) {
$variant[$k] = $option->getName();
}
}
}
if (strpos($product->getProductNumber(),'.') !== false) {
$pid = explode('.', $product->getProductNumber())[0];
} else {
$pid = $product->getProductNumber();
}
$ana = [
'pid' => $pid,
'group' => $group,
'var1' => $variant['econdWebAnalytics.config.var1'],
'var2' => $variant['econdWebAnalytics.config.var2'],
'var3' => $variant['econdWebAnalytics.config.var3']
];
$page->addExtension('ANA', new ArrayEntity($ana));
}
private function findTreeItemByCategoryId(string $categoryId, array $tree)
{
if (isset($tree[$categoryId])) {
return $tree[$categoryId];
}
foreach ($tree as $item) {
if (count($item->getChildren()))
{
$nested = $this->findTreeItemByCategoryId($categoryId, $item->getChildren());
if ($nested) {
return $nested;
}
}
}
return null;
}
}