Skip to content

Commit

Permalink
Merge pull request #23 from stape-io/feature/new-logic-updates
Browse files Browse the repository at this point in the history
Implemented new GTM code generation logic
  • Loading branch information
Bukashk0zzz authored Sep 27, 2024
2 parents 8730b6f + 6f2a862 commit ab11656
Show file tree
Hide file tree
Showing 19 changed files with 446 additions and 15 deletions.
53 changes: 49 additions & 4 deletions Block/Gtm.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,23 @@ public function __construct(
$this->configProvider = $configProvider;
}

/**
* Retrieve container id
*
* @return string
*/
protected function getStapeContainerId()
{
$containerId = str_ireplace('GTM-', '', $this->configProvider->getContainerId());
$params = $this->configProvider->getContainerIdParams();
$containerId = http_build_query(array_merge(
['id' => $this->_escaper->escapeJs($containerId)],
$this->getAdditionalQueryParams()
));

return http_build_query(array_merge([$params['prefix'] => base64_encode($containerId)], $params['suffix']));
}

/**
* Retrieve domain
*
Expand All @@ -47,7 +64,11 @@ public function getDomain()
*/
public function getLoader()
{
return trim($this->configProvider->getCustomLoader() ?: 'gtm', '/');
if (!$customLoader = $this->configProvider->getCustomLoader()) {
return 'gtm';
}

return implode('', [$this->configProvider->getCustomLoaderPrefix(), $customLoader]);
}

/**
Expand All @@ -57,10 +78,11 @@ public function getLoader()
*/
public function getContainerId()
{
if ($this->configProvider->getCustomDomain() && $this->configProvider->getCustomLoader()) {
return str_ireplace('GTM-', '', $this->configProvider->getContainerId());
if ($this->configProvider->getCustomLoader()) {
return $this->getStapeContainerId();
}
return $this->configProvider->getContainerId();

return $this->_escaper->escapeJs($this->configProvider->getContainerId());
}

/**
Expand Down Expand Up @@ -115,4 +137,27 @@ public function getIdParamName()
{
return $this->configProvider->getCustomLoader() && $this->configProvider->getCustomDomain() ? 'st' : 'id';
}

/**
* Retrieve analytics param
*
* @return string
*/
public function getAnalyticsParam()
{
return $this->configProvider->isStapeAnalyticsEnabled() && !empty($this->configProvider->getCustomLoader())
? 'y' : '';
}

/**
* Retrieve additional query params
*
* @return string[]
*/
public function getAdditionalQueryParams()
{
return array_filter([
'as' => $this->getAnalyticsParam(),
]);
}
}
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Changelog

v1.0.19
- Implemented custom GTM loader generation logic with prefix as well as container id

v1.0.18
- Fixed potential issue with sending multiple purchase webhook events.

Expand Down
139 changes: 139 additions & 0 deletions Model/Backend/CustomLoader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
<?php

namespace Stape\Gtm\Model\Backend;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Stape\Gtm\Model\ConfigProvider;
use Stape\Gtm\Model\Data\RandomString;
use Stape\Gtm\Model\Data\RandomSuffix;

class CustomLoader extends \Magento\Framework\App\Config\Value
{
/**
* @var RandomString $randomString
*/
private $randomString;

/**
* @var RandomSuffix $randomSuffix
*/
private $randomSuffix;

/**
* @var \Magento\Config\Model\ConfigFactory $configFactory
*/
private $configFactory;

/**
* @var Json $jsonSerializer
*/
private $jsonSerializer;

/**
* Define class dependencies
*
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param ScopeConfigInterface $config
* @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
* @param RandomString $randomString
* @param RandomSuffix $randomSuffix
* @param \Magento\Framework\Serialize\Serializer\Json $jsonSerializer
* @param \Magento\Config\Model\ConfigFactory $configFactory
* @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Stape\Gtm\Model\Data\RandomString $randomString,
\Stape\Gtm\Model\Data\RandomSuffix $randomSuffix,
\Magento\Config\Model\ConfigFactory $configFactory,
\Magento\Framework\Serialize\Serializer\Json $jsonSerializer,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
$this->randomString = $randomString;
$this->randomSuffix = $randomSuffix;
$this->configFactory = $configFactory;
$this->jsonSerializer = $jsonSerializer;
}

/**
* Save loader prefix
*
* @return void
* @throws \Exception
*/
protected function saveLoaderPrefix()
{
$prefix = $this->randomString->generate(5);
$config = $this->configFactory->create();
$config->setScope($this->getScope());
$config->setScopeId($this->getScopeId());
$config->setSection('stape_gtm');
$config->setDataByPath(ConfigProvider::XPATH_GTM_LOADER_PREFIX, $prefix);
$config->save();
}

/**
* Save container id params
*
* @return void
* @throws \Exception
*/
protected function saveContainerIdParams()
{
parse_str($this->randomSuffix->generate($this->getValue()), $suffix);
$value = $this->jsonSerializer->serialize([
'prefix' => $this->randomString->generate(),
'suffix' => $suffix,
]);

$config = $this->configFactory->create();
$config->setScope($this->getScope());
$config->setScopeId($this->getScopeId());
$config->setSection('stape_gtm');
$config->setDataByPath(ConfigProvider::XPATH_GTM_CONTAINER_ID_PARAMS, $value);
$config->save();
}

/**
* Actions after saving
*
* @return CustomLoader
*/
public function afterSave()
{
$loader = $this->getValue();

try {

$prefix = $this->_config->getValue(ConfigProvider::XPATH_GTM_LOADER_PREFIX, $this->getScope(), $this->getScopeId());

if (!empty($loader) && empty($prefix)) {
$this->saveLoaderPrefix();
}

$params = $this->_config->getValue(
ConfigProvider::XPATH_GTM_CONTAINER_ID_PARAMS,
$this->getScope(),
$this->getScopeId()
);

if (!empty($loader) && empty($params)) {
$this->saveContainerIdParams();
}
} catch (\Throwable $e) {

}

return parent::afterSave();
}
}
73 changes: 70 additions & 3 deletions Model/ConfigProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Stape\Gtm\Model;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Store\Model\ScopeInterface;

class ConfigProvider
Expand All @@ -17,6 +18,11 @@ class ConfigProvider
*/
public const XPATH_GTM_CONTAINER_ID = 'stape_gtm/general/container_id';

/*
* XPATH for GTM container id params config value
*/
public const XPATH_GTM_CONTAINER_ID_PARAMS = 'stape_gtm/general/container_id_params';

/*
* XPATH for GTM domain config value
*/
Expand All @@ -27,6 +33,16 @@ class ConfigProvider
*/
public const XPATH_GTM_LOADER = 'stape_gtm/general/custom_loader';

/*
* XPATH for GTM Custom Loader prefix config value
*/
public const XPATH_GTM_LOADER_PREFIX = 'stape_gtm/general/custom_loader_prefix';

/*
* XPATH for Stape analytics
*/
public const XPATH_GTM_STAPE_ANALYTICS_ENABLED = 'stape_gtm/general/stape_analytics_enabled';

/*
* XPATH for GTM Cookie Keeper config value
*/
Expand Down Expand Up @@ -67,14 +83,23 @@ class ConfigProvider
*/
private $scopeConfig;

/**
* @var Json $jsonSerializer
*/
private $jsonSerializer;

/**
* Define class dependencies
*
* @param ScopeConfigInterface $scopeConfig
* @param Json $jsonSerializer
*/
public function __construct(ScopeConfigInterface $scopeConfig)
{
public function __construct(
ScopeConfigInterface $scopeConfig,
Json $jsonSerializer
) {
$this->scopeConfig = $scopeConfig;
$this->jsonSerializer = $jsonSerializer;
}

/**
Expand Down Expand Up @@ -121,6 +146,48 @@ public function getCustomLoader($scopeCode = null)
return $this->scopeConfig->getValue(self::XPATH_GTM_LOADER, ScopeInterface::SCOPE_STORE, $scopeCode);
}

/**
* Retrieve encoded customer loader
*
* @param string|int $scopeCode
* @return string
*/
public function getCustomLoaderPrefix($scopeCode = null)
{
return $this->scopeConfig->getValue(self::XPATH_GTM_LOADER_PREFIX, ScopeInterface::SCOPE_STORE, $scopeCode);
}

/**
* Retrieve container id params
*
* @param string|int $scopeCode
* @return array
*/
public function getContainerIdParams($scopeCode = null)
{
$value = $this->scopeConfig->getValue(
self::XPATH_GTM_CONTAINER_ID_PARAMS,
ScopeInterface::SCOPE_STORE,
$scopeCode
);
return $this->jsonSerializer->unserialize($value ?? '');
}

/**
* Check if stape analytics is enabled
*
* @param string|int $scopeCode
* @return bool
*/
public function isStapeAnalyticsEnabled($scopeCode = null)
{
return $this->scopeConfig->isSetFlag(
self::XPATH_GTM_STAPE_ANALYTICS_ENABLED,
ScopeInterface::SCOPE_STORE,
$scopeCode
);
}

/**
* Check if cookie keeper should be used
*
Expand All @@ -135,7 +202,7 @@ public function useCookieKeeper($scopeCode = null)
/**
* Check if datalayer e-commerce events tracking is enabled
*
* @param string}null $scopeCode
* @param string|null $scopeCode
* @return bool
*/
public function ecommerceEventsEnabled($scopeCode = null)
Expand Down
32 changes: 32 additions & 0 deletions Model/Data/RandomString.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Stape\Gtm\Model\Data;

class RandomString
{
/**
* Generate random string
*
* @param int $length
* @return string
*/
public function generate(int $length = 8)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = rand(1, $length); // Random length between 1 and 8
$randomString = '';

for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}

// Check if the string ends with 'kp' or 'gt'
while (in_array(substr($randomString, -2), ['kp', 'gt'])) {
$randomString = substr($randomString, 0, -2); // Remove last two characters
$randomString .= $characters[rand(0, strlen($characters) - 1)];
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}

return $randomString;
}
}
Loading

0 comments on commit ab11656

Please sign in to comment.