<?php
namespace Elements\Bundle\TrackingBundle\Service;
use Pimcore\Bundle\EcommerceFrameworkBundle\Tracking\AbstractProductData;
use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag;
use Symfony\Component\HttpFoundation\RequestStack;
use Pimcore\Bundle\EcommerceFrameworkBundle\Tracking\ProductAction;
class Ga4Service
{
protected $requestStack;
/**
* Ga4Service constructor
*
* @param RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function addProductToList(AbstractProductData $product, string $list): void
{
$request = $this->requestStack->getCurrentRequest();
if ($request->hasSession()) {
$productId = $product->getId();
$session = $request->getSession();
/** @var NamespacedAttributeBag $bag */
$bag = $session->getBag('session_ga4');
if (!$productList = $bag->get('product_list')) {
$productList = [];
}
if (!$fixedList = $bag->get('product_fixed_list')) {
$fixedList = [];
}
if (!array_key_exists($productId, $fixedList) || !$fixedList[$productId]) {
$productList[$productId] = $list;
$fixedList[$productId] = false;
// Add other related product ids to session
$attributes = $product->getAdditionalAttributes();
if (array_key_exists('product_ids', $attributes)) {
$additionalProductIds = $attributes['product_ids'];
foreach($additionalProductIds as $id) {
$productList[$id] = $list;
$fixedList[$id] = false;
}
}
}
$bag->set('product_fixed_list', $fixedList);
$bag->set('product_list', $productList);
}
}
public function getListOfProduct(AbstractProductData $product): string
{
$request = $this->requestStack->getCurrentRequest();
if ($request->hasSession()) {
$session = $request->getSession();
$productList = $session->getBag('session_ga4')->get('product_list');
if (!$productList) {
#this can only be, if the produkt-link is opened directly -> list "default"
return 'default';
}
if (array_key_exists($product->getId(), $productList)) {
return $productList[$product->getId()];
}
}
#this can only be, if the produkt-link is opened directly -> list "default"
return 'default';
}
public function fixateListName(ProductAction $product): void
{
$request = $this->requestStack->getCurrentRequest();
if ($request->hasSession()) {
$session = $request->getSession();
/** @var NamespacedAttributeBag $bag */
$bag = $session->getBag('session_ga4');
if (!$fixedList = $bag->get('product_fixed_list')) {
$fixedList = [];
}
$fixedList[$product->getId()] = true;
$bag->set('product_fixed_list', $fixedList);
}
}
}